Android应用程序资源

引用样式属性

?[<package_name>:][<resource_type>/]<resource_name>  

  应用当前主题下的指定属性值
    <EditText id="text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:textColor="?android:textColorSecondary"
      android:text="@string/hello_world" />


捕获运行时配置变化

  屏幕方向、键盘有效性和语言等配置的变化通常引起Android重启正在运行的Activity(OnDestroy被调用,紧接着调用OnCreate)。
一、通过以下方法保存数据

    //onRetainNonConfigurationInstance被调用在OnStop和OnDestory之间

    //MyDataObject对象不能保有任何与Context相关联的数据(Drawable、Adapter、View等),以防止内存泄露

    //不可用Bundle,Bundle在保存大数据量状态时需要序列化与反序列化,会消费很多内存并可能会是配置的变化过程变慢
    @Override
    public Object onRetainNonConfigurationInstance() {
      final MyDataObject data = collectMyLoadedData();
      return data;
    }

 

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
      if (data == null) {
        data = loadMyData();
      }
      ...
    }
   
二、也可以声明由自己捕获运行时配置变化,以避免Android重启Activity
    <activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">
  当上述声明的运行时配置发生变化时,将会接收到onConfigurationChanged事件

    //当未声明的运行时配置发生变化时,Android依然会重启正在运行的Activity
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);

      // Checks the orientation of the screen
      if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
      } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
      }
      // Checks whether a hardware keyboard is available
      if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
      } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
      }
    }

你可能感兴趣的:(android)