package com.example.screenorientation;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/*
* 為了不讓每次的螢幕翻轉都重新跑一次onCreate() 要在Androidmanifest加上 4.0以上的作法
* android:configChanges="orientation|keyboardHidden|screenSize"
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dm = getResources().getDisplayMetrics();
// 取得螢幕顯示的資料
ScreenWidth = dm.widthPixels;
ScreenHeight = dm.heightPixels;
// 螢幕寬和高的Pixels
if (ScreenHeight > ScreenWidth)
setContentView(R.layout.activity_main);
else
setContentView(R.layout.activity_two);
}
DisplayMetrics dm;
int ScreenWidth, ScreenHeight;
int oldOrientation = -1;
// Configuration.ORIENTATION_LANDSCAPE Constant Value: 2
// Configuration.ORIENTATION_PORTRAIT Constant Value: 1
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// 橫轉直會多跑一次 , 所以加上判斷過濾
if (oldOrientation != newConfig.orientation) {
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 橫向
setContentView(R.layout.activity_two);
} else {
// 直向
setContentView(R.layout.activity_main);
}
oldOrientation = newConfig.orientation;
}
}
}
全站熱搜
留言列表