Android 切换横竖屏

【Android 切换横竖屏】时人不识凌云木,直待凌云始道高。这篇文章主要讲述Android 切换横竖屏相关的知识,希望能为你提供帮助。
一个项目一般会自己先定义项目是横屏还是竖屏但是也有可以横屏和竖屏之间切换的activty。
切换横竖屏的方法: 

//判断当前屏幕方向
if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//切换竖屏
MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}else{
//切换横屏
MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}


但是这样切换横竖屏会让activity重新加载。生命周期为:
onStop
onDestroy
onCreate
onStart
onResume
为了解决这样的问题在配置文件里加上
android:configChanges="orientation|keyboardHidden|screenSize"


就不会重新加载页面,只会进入到切换里面的生命周期中。
onConfigurationChanged
 
AndroidManifest.xml
< activity android:name=".MainActivity" android:configChanges="orientation|keyboardHidden|screenSize" > < intent-filter> < action android:name="android.intent.action.MAIN" /> < category android:name="android.intent.category.LAUNCHER" /> < /intent-filter> < /activity>

MainActivity.java
package com.kkrs.change; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity {private Button change; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); change = (Button)findViewById(R.id.change); Log.e("sys","onCreate"); }@Override protected void onStart() { super.onStart(); Log.e("sys","onStart"); change.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("sys","被点击了"); //判断当前屏幕方向 if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { //切换竖屏 MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }else{ //切换横屏 MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }} }); }//横竖屏切换 @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.e("sys","onConfigurationChanged"); }@Override protected void onStop() { super.onStop(); Log.e("sys","onStop"); }@Override protected void onResume() { super.onResume(); Log.e("sys","onResume"); }@Override protected void onDestroy() { super.onDestroy(); Log.e("sys","onDestroy"); } }



















    推荐阅读