【问题标题】:Code to detect mobile and tablet not working [duplicate]检测手机和平板电脑不工作的代码[重复]
【发布时间】:2014-02-10 22:58:18
【问题描述】:

在我的应用程序中,UI 是根据手机或平板电脑更改的。所以我正在为手机和平板电脑使用 2 个课程。

在模拟器中运行良好。但在真正的平板设备中它不起作用,它需要移动设备类。

检测设备的我的代码:

public boolean isTablet(Context context) 
{
   boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
   boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
   return (xlarge || large);    
}

我的代码有什么问题。我只在真实设备上获得移动布局。

【问题讨论】:

    标签: android mobile-devices


    【解决方案1】:

    在 Android 开发中检查什么样的设备是非常不准确的。试试我的代码

    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;
    }
    

    【讨论】:

    • 它不适合我
    猜你喜欢
    • 2012-03-20
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多