JAVA代码
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
Kotlin代码
val screenWidth = windowManager.defaultDisplay.width
val screenHeight = windowManager.defaultDisplay.height
已经补标记过时,不推荐使用。
Java代码
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
Kotlin代码
val dm = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(dm)
val screenWidth = dm.widthPixels
val screenHeight = dm.heightPixels
Java代码
Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
Kotlin代码
val resources: Resources = this.resources
val dm: DisplayMetrics = resources.displayMetrics
val screenWidth = dm.widthPixels
val screenHeight = dm.heightPixels
前面三种获取的值单位是px,这一种得到的是dp值。
Java代码
Configuration config = getResources().getConfiguration();
int screenWidth = config.screenWidthDp;
int screenHeight = config.screenHeightDp;
Kotlin代码
val config: Configuration = resources.configuration
val screenWidth = config.screenWidthDp
val screenHeight = config.screenHeightDp
Compose中获取
val config = LocalConfiguration.current
val screenWidth = config.screenWidthDp
val screenHeight = config.screenHeightDp