關於android:configChanges="keyboardHidden|orienta...

常見的android應用程序在AndroidManifest.xml文件中都沒有使用到android:configChanges="keyboardHidden|orientation"配置。
它仍是頗有用的。若是配置了這個屬性,當咱們橫豎屏切換的時候會直接調用onCreate方法中的onConfigurationChanged方法,而不會從新執行onCreate方法,那固然若是不配置這個屬性的話就會從新調用onCreate方法了。 java

測試: android

AndroidManifest.xml文件 app

複製代碼

<?xml version="1.0" encoding="utf-8"?>  ide

<manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.test"      android:versionCode="1"           android:versionName="1.0">  測試

    <uses-sdk android:minSdkVersion="8" />      <application android:icon="@drawable/icon"          android:label="@string/app_name">          <activity android:name=".TestActivity"              android:label="@string/app_name"              android:configChanges="keyboardHidden|orientation">              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />          </intent-filter>          </activity>      </application> </manifest> spa

複製代碼

main.xml文件 .net

複製代碼

<?xml version="1.0" encoding="utf-8"?> code

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"          android:orientation="vertical"         android:layout_width="fill_parent"         android:layout_height="fill_parent" >          <TextView android:id="@+id/tv"             android:layout_width="fill_parent"             android:layout_height="wrap_content"             android:text="橫豎屏切換測試" />          <EditText android:layout_width="fill_parent"              android:layout_height="wrap_content"             android:id="@+id/et" />  </LinearLayout> xml

複製代碼

TestActivity.java文件 utf-8

複製代碼

package com.test;

import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; public class TestActivity extends Activity {

EditText et; TextView tv; @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState); setContentView(R.layout.main); et = (EditText) findViewById(R.id.et); tv = (TextView) findViewById(R.id.tv); System.out.println("我是onCreate方法"); } @Override     public void onConfigurationChanged(Configuration newConfig) {         super.onConfigurationChanged(newConfig);          if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){             tv.setText("橫屏");

} else { tv.setText("豎屏"); } } }

複製代碼

能夠親自測試測一下,以驗證上述結論
當在xml文件中配置了android:configChanges="keyboardHidden|orientation"屬性,
在橫緊屏切換的時候不會從新執行Activity的onCreate方法,
只是執行onConfigurationChanged方法,不然切換的時候會從新執行onCreate方法

相關文章
相關標籤/搜索