Android之屏幕方向改变以及onConfigurationChanged事件

来源:互联网 发布:兄弟连linux视频教程 编辑:程序博客网 时间:2024/05/06 15:04
 

注意:onConfigurationChanged事件并不是只有屏幕方向改变才可以触发,其他的一些系统设置改变也可以触发,比如打开或者隐藏键盘。

当我们的屏幕方向发生改变时,就可以触发onConfigurationChanged事件。我们要想当前的activity捕获这个事件,需要做以下这么几件事情。
 

第一:权限声明:

<uses-permission Android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>

API中说该权限允许我们改变配置信息,但是我们再改变屏幕方向的程序中却并没有用到该权限,是不是相互冲突了呢?这里我们可以这样认为,当我们声明该权限的的时候,系统允许我们通过重写activity中的onConfigurationChanged方法来捕获和修改某些配置信息。

第二:声明activity要捕获的事件类型,

<activity
      Android:name=".EX05_23"
      Android:label="@string/app_name"
      Android:configChanges="orientation|keyboard">
      <intent-filter>
        <action Android:name="android.intent.action.MAIN" />
        <category Android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

这里一定要声明Android:configChanges属性,该属性规定了我们可以在程序中捕获到的事件类型,多个事件类型用|分隔。

如果这里没有orientation,那么我们再程序中是无法捕获到屏幕改变的事件的。

第三:

重写Activity中的onConfigurationChanged方法。

例如:


 @Override
 public void onConfigurationChanged(Configuration newConfig) {
  // 当新设置中,屏幕布局模式为横排时
  if(newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
  {
   //TODO 某些操作
  }
  super.onConfigurationChanged(newConfig);
 }

 

 

防止再次调用onCreate,首先,需要设置android:configChanges,可选属性如下:
ValueDescriptionmccThe IMSI mobile country code (MCC) has changed — that is, a SIM hasbeen detected and updated the MCC.移动国家号码,由三位数字组成,每个国家都有自己独立的MCC,可以识别手机用户所属国家。mncThe IMSI mobile network code (MNC) has changed — that is, a SIM hasbeen detected and updated the MNC.移动网号,在一个国家或者地区中,用于区分手机用户的服务商。localeThe locale has changed — for example, the user has selected a new language that text should be displayed in.用户所在地区发生变化。touchscreenThe touchscreen has changed. (This should never normally happen.)keyboardThe keyboard type has changed — for example, the user has plugged in an external keyboard.键盘模式发生变化,例如:用户接入外部键盘输入。keyboardHiddenThe keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.用户打开手机硬件键盘navigationThe navigation type has changed. (This should never normally happen.)orientationThe screen orientation has changed — that is, the user has rotated the device.设备旋转,横向显示和竖向显示模式切换。fontScaleThe font scaling factor has changed — that is, the user has selected a new global font size.全局字体大小缩放发生改变这里关于屏幕旋转不需要再次调用onCreate是应该设置android:configChanges="orientation|keyboardHidden"
然后重载onConfigurationChanged

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2011-06/36828.htm