第一種
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