Android判断当前设备是手机还是平板以及dp与pix的转换
2016-09-23 16:02
597 查看
Android开发需要适配手机和平板,有些需求实现时就要求判断设备是手机还是平板。
网上很多说通过设备尺寸、DPI、版本号、是否具备电话功能等进行判断,不过都不算太精确。
这里分享一个简洁给力的方法(官方用法):
令附上是否具备电话功能判断方法(现在部分平板也可以打电话):
至于设备尺寸、分辨率、版本号,以目前手机来看,个人认为精度太差了,不建议使用。
========================================================================================
网上很多说通过设备尺寸、DPI、版本号、是否具备电话功能等进行判断,不过都不算太精确。
这里分享一个简洁给力的方法(官方用法):
/** * 判断当前设备是手机还是平板,代码来自 Google I/O App for Android * @param context * @return 平板返回 True,手机返回 False */ public static boolean isPad(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; }
令附上是否具备电话功能判断方法(现在部分平板也可以打电话):
public static boolean isPad(Activity activity) { TelephonyManager telephony = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE); if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) { return true; }else { return false; } }
至于设备尺寸、分辨率、版本号,以目前手机来看,个人认为精度太差了,不建议使用。
========================================================================================
/** * This method converts dp unit to equivalent pixels, depending on device density. * * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels * @param context Context to get resources and device specific display metrics * @return A float value to represent px equivalent to dp depending on device density */ public static float convertDpToPixel(float dp, Context context){ Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return px; } /** * This method converts device specific pixels to density independent pixels. * * @param px A value in px (pixels) unit. Which we need to convert into db * @param context Context to get resources and device specific display metrics * @return A float value to represent dp equivalent to px value */ public static float convertPixelsToDp(float px, Context context){ Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return dp; }
相关文章推荐
- Android 判断当前设备是手机还是平板
- Android 判断当前设备是手机还是平板
- Android 判断当前设备是手机还是平板
- Android 判断当前设备是手机还是平板
- Android 判断当前设备是手机还是平板
- Android 编程下判断当前设备是手机还是平板
- Android 判断当前设备是手机还是平板
- Android 编程下判断当前设备是手机还是平板
- Android 判断当前设备是手机还是平板
- Android - 判断Android设备是手机还是平板?
- 如何判断Android设备是手机还是平板?
- 如何判断Android设备是手机还是平板?
- 如何判断Android设备是手机还是平板?
- 如何判断Android设备是手机还是平板?
- 如何程序判断当前设备是手机还是平板
- 判断当前设备是平板还是手机
- 判断当前设备是手机还是平板
- Android判断设备是手机还是平板
- Android之如何判断设备是平板还是手机
- 判断当前设备是平板还是手机!