需要在AndroidManifest.xml增加代码:
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<activity
android:name="HelloWorldActivity"
android:label="@string/title_name"
android:configChanges="orientation|keyboard|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
然后在Activity的子类下重写(import android.content.res.Configuration; ----->导入import快捷:CTRL+SHIFT+O):
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
try {
if(this.getResources().getConfiguration().orientation == newConfig.ORIENTATION_LANDSCAPE){
Log.v("orientation", "ORIENTATION_LANDSCAPE");
Toast.makeText(getApplication(), "ORIENTATION_LANDSCAPE(横屏)", Toast.LENGTH_LONG).show();
} else if(this.getResources().getConfiguration().orientation == newConfig.ORIENTATION_PORTRAIT){
Log.v("orientation", "ORIENTATION_PORTRAIT");
Toast.makeText(getApplication(), "ORIENTATION_PORTRAIT(竖屏)", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}