Android 横竖屏切换 状态保留

添加菜单

java文件

// Menu菜单添加
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "关于").setIcon(R.drawable.icon);
		menu.add(0, 1, 1, "横竖切换");
		menu.add(0, 2, 2, "退出");
		return super.onCreateOptionsMenu(menu);
	}

	// Menu菜单功能添加
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 0:
			Toast.makeText(getApplicationContext(), "2011 By 某某某", Toast.LENGTH_LONG).show();
			break;
		case 1:
			// 如果是竖排,则改为横排
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
			// 如果是横排,则改为竖排
			else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			}
			break;
		case 2:
			// 程序切换
			this.finish();
			break;
		}
		return true;
	}
AndroidManifest.xml

设置初始为竖屏

android:screenOrientation="portrait"
设置切换屏幕后画面数据保留(这句很关键)

android:configChanges="orientation|keyboardHidden"

完整xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.android.test" android:versionCode="1"
	android:versionName="1.0">
	<application android:label="@string/app_name" android:icon="@drawable/icon">
		<activity android:label="@string/app_name" android:name="HelloWorld"
			android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

	</application>
	<uses-sdk android:minSdkVersion="4" />
</manifest> 


你可能感兴趣的:(java,android,application,menu,encoding)