本文共 2127 字,大约阅读时间需要 7 分钟。
Android重写onConfigurationChanged规避横竖屏切换时候重新进入onCreate生命周期
Android系统内在的机制,当activity在横竖屏切换时候,会强制重新开始进入activity的生命周期onCreate,在有些特殊的场景,开发者不希望重新进入onCreate生命周期,那么,可以通过重写Android的onConfigurationChanged规避。
具体做法: (1)添加权限:(2)因为需要在activity里面检测横竖屏幕的切换变化,故而在Androidmanifest.xml里面配置目标activity的属性:
android:configChanges="orientation|screenSize"
至此,完整的Androidmanifest.xml文件:
(3)接下来就是重写activity里面的onConfigurationChanged:
@Override public void onConfigurationChanged(Configuration newConfig) { if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // 当前为横屏 Log.d(tag, "ORIENTATION_LANDSCAPE=" + Configuration.ORIENTATION_LANDSCAPE);// 2 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // 当前为竖屏 Log.d(tag, "ORIENTATION_PORTRAIT=" + Configuration.ORIENTATION_PORTRAIT);// 1 } super.onConfigurationChanged(newConfig); }
完整的测试MainActivity.java代码文件:
package zhangphil.config;import android.app.Activity;import android.content.res.Configuration;import android.os.Bundle;import android.util.Log;import android.widget.Toast;public class MainActivity extends Activity { private final String tag = "zhangphil"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toast.makeText(this, "onCreate @ " + System.currentTimeMillis(), Toast.LENGTH_SHORT).show(); } @Override public void onConfigurationChanged(Configuration newConfig) { if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // 当前为横屏 Log.d(tag, "ORIENTATION_LANDSCAPE=" + Configuration.ORIENTATION_LANDSCAPE);// 2 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // 当前为竖屏 Log.d(tag, "ORIENTATION_PORTRAIT=" + Configuration.ORIENTATION_PORTRAIT);// 1 } super.onConfigurationChanged(newConfig); }}
转载地址:http://kcvwx.baihongyu.com/