Android 螢幕相關 小筆記

摘要:Android 螢幕相關 小筆記

1. 取得螢幕大小


DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
width = dm.widthPixels;
height = dm.heightPixels;

 

2. 選轉螢幕不讓 activity 重啟(官方文件)


<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden|screenSize"
          android:label="@string/app_name">

    screenSize 於Android 3.2 (API level 13) 才需要


@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

 

3.鎖定螢幕的旋轉 ( 直 portrait , 橫 landscape )


<activity android:name=".MyActivity"          
          android:label="@string/app_name"
          android:screenOrientation="portrait" >

 

4.控制轉為直的或橫的


setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);