一、对于设备是否为平板的判断
最近有需求对横屏进行适配,其中有个地方需要区分是手机还是平板设备,所以对是否为平板的判断研究了一下,这里做一个记录。话不多说,上代码
object DeviceTypeUtils {
/**
* @MethodName: isPad
* @Description: 是否是平板
* @author dev_zzx
* @param context 上下文
* @return 是平板则返回true,反之返回false
*/
fun isPad(context: Context): Boolean {
val isPad: Boolean = (context.resources.configuration.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
var screenInches = 0.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//安卓11及以上
val bounds = wm.currentWindowMetrics.bounds
context.display?.let {
val densityDpi = context.resources.configuration.densityDpi
val x = (bounds.width() / densityDpi).toDouble().pow(2.0)
val y = (bounds.height() / densityDpi).toDouble().pow(2.0)
screenInches = sqrt(x + y) // 屏幕尺寸
}
} else {
//安卓11以下
val display: Display = wm.defaultDisplay
val dm = DisplayMetrics()
display.getMetrics(dm)
val x = (dm.widthPixels / dm.xdpi).toDouble().pow(2.0)
val y = (dm.heightPixels / dm.ydpi).toDouble().pow(2.0)
screenInches = sqrt(x + y) // 屏幕尺寸
}
return if (screenInches == 0.0) {
//屏幕尺寸计算异常
isPad
}else {
isPad && screenInches >= 7.0
}
}
}
这里由于WindowManager获取defaultDisplay从而获取屏幕分辨率的方法过期了,所以进行了版本的判断。不过现在手机的屏幕尺寸越来越大了,不清楚市面上是否已经有7英寸的手机,所以本方法就目前而言是相对可用的。后面就得修改判断尺寸的大小啦。
二、当横屏90度时(刘海向左)旋转到横屏270度(刘海向右)
此时就算AndroidManifest.xml中声明了如下
android:configChanges="orientation|keyboard|keyboardHidden|screenSize|uiMode"
android:screenOrientation="unspecified"
OnConfigurationChanged也不会被触发。做了在传感器监听中对旋转角度进行判断的尝试,但是效果不佳,所以这种场景暂时没有对其进行适配。