Tablet or Phone - Android

后端 未结 30 2171
难免孤独
难免孤独 2020-11-22 08:33

Is there a way to check if the user is using a tablet or a phone? I\'ve got problems with my tilt function and my new tablet (Transformer)

30条回答
  •  醉酒成梦
    2020-11-22 09:02

    This post helped me a lot,

    Unfortunately I don't have the reputation necessary to evaluate all the answers that helped me.

    I needed to identify if my device was a tablet or a phone, with that I would be able to implement the logic of the screen. And in my analysis the tablet must be more than 7 inches (Xlarge) starting at MDPI.

    Here's the code below, which was created based on this post.

    /**
     * Checks if the device is a tablet or a phone
     * 
     * @param activityContext
     *            The Activity Context.
     * @return Returns true if the device is a Tablet
     */
    public static boolean isTabletDevice(Context activityContext) {
        // Verifies if the Generalized Size of the device is XLARGE to be
        // considered a Tablet
        boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & 
                            Configuration.SCREENLAYOUT_SIZE_MASK) == 
                            Configuration.SCREENLAYOUT_SIZE_XLARGE);
    
        // If XLarge, checks if the Generalized Density is at least MDPI
        // (160dpi)
        if (xlarge) {
            DisplayMetrics metrics = new DisplayMetrics();
            Activity activity = (Activity) activityContext;
            activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
            // MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
            // DENSITY_TV=213, DENSITY_XHIGH=320
            if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
                    || metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
                    || metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
                    || metrics.densityDpi == DisplayMetrics.DENSITY_TV
                    || metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
    
                // Yes, this is a tablet!
                return true;
            }
        }
    
        // No, this is not a tablet!
        return false;
    }
    

提交回复
热议问题