默认情况下,当屏幕方面切换时,activity的onCreate()方法会被重新调用,所以可以在其中通过以下代码来读取屏的方向:
public void onCreate() {
if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.i("info", "landscape");
} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.i("info", "portrait");}}
如果在androidmanifest.xml中加入配置
android:configChanges="orientation|keyboardHidden|navigation
当屏幕翻转时,Activity就不会重复的调用onCreate()、onPause()和onResume().
而是调用onConfigurationChanged(Configuration newConfig)
int screenWidth,screenHeight;
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
screenWidth = display.getWidth();
screenHeight = display.getHeight();
也有另一种方法:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
Android程序如何获得屏幕的方向和大小
最新推荐文章于 2023-12-04 14:51:26 发布
本文详细介绍了在Android应用中,如何在屏幕方向变化时,通过检查屏幕方向并使用配置变化来避免不必要的Activity生命周期方法调用,以及如何获取屏幕宽度和高度。包括配置更改时的回调方法和屏幕尺寸获取的两种方法。
3801

被折叠的 条评论
为什么被折叠?



