• Android onConfigurationChanged用法(规避横竖屏切换导致的重新调用onCreate方法)


    onConfigurationChanged的目的是为了规避横竖屏切换干掉activity而重新调用onCreate方法的问题;
    有的时候,我们希望重新进入OnCreate生命周期,此时可以调用onSaveInstanceState和onRestoreInstanceState方法,可参考http://www.cnblogs.com/leavescy/p/7845921.html;
    而有的时候,我们又不希望这种事情发誓,所以就要重写onConfigurationChanged方法;
    1. 在AndroidManifest.xml中添加一些权限:
     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>

    2. 配置目标activity属性:
    android:configChanges="orientation|screenSize">

    如下所示:
     1 <?xml version="1.0" encoding="utf-8"?>
     2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     3     package="com.xxx.dictionarychange">
     4 
     5     <application
     6         android:allowBackup="true"
     7         android:icon="@mipmap/ic_launcher"
     8         android:label="@string/app_name"
     9         android:roundIcon="@mipmap/ic_launcher_round"
    10         android:supportsRtl="true"
    11         android:theme="@style/AppTheme">
    12         <activity android:name=".MainActivity"
    13                   android:configChanges="orientation|screenSize">
    14             <intent-filter>
    15                 <action android:name="android.intent.action.MAIN" />
    16 
    17                 <category android:name="android.intent.category.LAUNCHER" />
    18             </intent-filter>
    19         </activity>
    20 
    21 
    22     </application>
    23     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>
    24 
    25 </manifest>
    
    

    3. 最后在MainActivity.java中重写onConfigurationChanged方法,如下所示:

    里面打印出来了一些日志,可以提示现在是横屏还是竖屏;

     @Override
        public void onConfigurationChanged(Configuration newConfig) {
            if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                Log.i("LANDSCAPE = ", String.valueOf(Configuration.ORIENTATION_LANDSCAPE));
            }
            else if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
                Log.i("LANDSCAPE = ", String.valueOf(Configuration.ORIENTATION_PORTRAIT));
    
            }
            super.onConfigurationChanged(newConfig);
        }
    
    
    
    



  • 相关阅读:
    【转】Spring高级进阶:BeanFactoryPostProcessor
    【转】2019版本idea导入新spring boot项目有关配置讲解及右侧没有maven解决方式
    jquery 选择器(name,属性,元素)大全
    【转】读懂正则表达式就这么简单
    【转】跨站脚本攻击(XSS)
    Oracle 分页查询 插叙不出数据
    spring:过滤器和拦截器
    Idea-每次修改JS文件都需要重启Idea才能生效解决方法 热部署
    IDEA: Call Hierarchy
    Linux之文件读取查看之cat、head、tail、tac、rev、more、less
  • 原文地址:https://www.cnblogs.com/leavescy/p/7868304.html
Copyright © 2020-2023  润新知