onConfigurationChanged方法监控系统更改事件
添加权限
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>
在manifest.xml中的activity中设置configuration的属性
<activity android:name=".ConfigChange" android:label="@string/app_name" android:configChanges="orientation|keyboard"> </activity>
代码,重写onConfigurationChanged方法
private Button button1;
private int width;
private int height;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_change);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
width = dm.widthPixels;
height = dm.heightPixels;
if (width < height) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
});
}
public void onConfigurationChanged(Configuration newConfig){
if(newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)toast("已切换为横屏");
else{
toast("已切换竖屏");
}
super.onConfigurationChanged(newConfig);
}
public void toast(String str) {
Toast.makeText(ConfigChange.this, str, Toast.LENGTH_LONG).show();
}