横竖屏切换android:configChanges的使用

package com.liupan.configchanges;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView text;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.e("横竖屏切换 onCreate", "onCreate");
		text = (TextView) findViewById(R.id.text);
		text.setText("屏幕方向");

	}

	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		Log.e("横竖屏切换 onConfigurationChanged", "onConfigurationChanged");
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			text.setText("当前为横屏");
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			text.setText("当前为竖屏");
		}
	}

}

默认不进行设置的话,手机的横竖屏切换会使当前的Activity重新构造,onPause ->onStop->onDestory-> onCreate ->onStart ->onResume.

如果不想这样的话,有两种方式:


 1. 直接设置屏幕为横屏或者竖屏    

            android:screenOrientation="landscape"
            android:screenOrientation="portrait"

这时也可以手动切换

	btn = (Button) findViewById(R.id.btn);
		btn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int oritentation = getRequestedOrientation();
				if (oritentation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				} else if (oritentation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
					setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				}

			}
		});


 2. 通过设置 android:configChanges="orientation|keyboardHidden“

        但是需要注意的是 :在Android3.2  API13以及以上系统中,需要再添加一个属性screenSize才行,orientation|keyboardHidden |screenSize,这样才能Activity不重新创建.






你可能感兴趣的:(横竖屏切换)