Android uses code to dynamically control the horizontal and vertical display of an interface according to the device type

Keywords: Android Mobile

background

The Android application developed was originally tested on the mobile phone, but it actually needs to be installed and used for the tablet. When it is on the mobile phone, the effect of vertical display is good, while that of horizontal display on the tablet is good. Therefore, it is necessary to judge whether it is horizontal screen display or vertical screen display according to the type of equipment. (actually, it's a map drawn with user-defined view!)

thinking

Let's talk about the ideas of implementation.
First, we need to determine whether the current device is a mobile phone or a tablet; after determining the device type, we can display the corresponding horizontal and vertical screens according to the corresponding type of device.

code implementation

The implementation is as follows:

package com.example.pc_2.carmapproject.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.example.pc_2.carmapproject.activity.MainActivity;

/**
 * Created by zouqi on 2018/2/9.
 */

public class ScreenUtil {

    /**
     * Determine the horizontal and vertical display mode of the map main interface according to the device type (mobile phone or tablet)
     * @param activity
     */
    public static void selectScreentDirection(Activity activity){
        if(!isTabletDevice(activity)){
            ToastUtil.showToast(activity, "The current device is a mobile device");
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// Set up vertical display
        }else {
            ToastUtil.showToast(activity, "The current device is a tablet device");
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// Setting the horizontal display
        }
    }

    /**
     * Judge whether the current device is a tablet
     * @param context
     * @return true Tablet, false phone
     */
    private static boolean isTabletDevice(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

}

I'll encapsulate the horizontal and vertical screen display in the tool class. You just need to call the onCreate method of the required activity (an interface), as follows:

ScreenUtil.selectScreentDirection(MainActivity.this);// Determine the horizontal and vertical display mode according to the device type

===========================================================================

A little bit of progress every day!Come on!

Posted by anauj0101 on Mon, 06 Apr 2020 08:36:02 -0700