如何在方向改变时包含android天文台的值

时间:2014-02-09 15:27:15

标签: android chronometer

我正在构建一个简单的计时器应用程序,其中我使用安卓计时器来跟踪时间的流逝。但是当我开始计时器并将方向更改为横向时,计时器重置并再次显示00:00。我希望它保留其价值。 portraitlandscape的布局不同

portrait--> Layout文件夹

landscape->layout_land文件夹

<Chronometer 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content"
    android:id="@+id/chronometer1"
    android:layout_above="@+id/button2"
    android:textStyle="bold"
    android:textColor="@color/Indigo"
    android:text="Chronometer"
    android:layout_toLeftOf="@+id/save_btn"
    android:typeface="serif"
    android:textSize="40dp"/>

1 个答案:

答案 0 :(得分:1)

以下是该文件所说的内容:

<强> Recreating an Activity

  

警告:每次用户旋转屏幕时,您的活动都将被销毁并重新创建。当屏幕更改方向时,系统会破坏并重新创建前台活动,因为屏幕配置已更改,您的活动可能需要加载其他资源(例如布局)。

如果您在更改方向之前需要Save activity's state,则必须覆盖onSaveInstanceState()。此方法将帮助您保存方向更改后要返回的所有值。然后使用onCreate()方法恢复它们。

这是一个例子:

String myVar;

/* 
     ...
*/
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save myVar's value in saveInstanceState bundle
    savedInstanceState.putString("myVar", myVar);
    super.onSaveInstanceState(savedInstanceState);
}

现在在创建活动时检索它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    // savedInstanceState is the bundle in which we stored myVar in onSaveInstanceState() method above
    // savedInstanceState == null means that activity is being created a first time
    if (savedInstanceState == null) {
        // some code here
        myVar = "first value";
    } else {  // savedInstance != null means that activity is being recreated and onSaveInstanceState() has already been called.
        myVar = savedInstanceState.getString("myVar");
    }
    /*
       ...
    */
}