如何通过方向更改包含Android计时码表的值 [英] How to contain value of android chronometer with change in orientation

查看:87
本文介绍了如何通过方向更改包含Android计时码表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的计时器应用,其中我使用android计时器来跟踪经过的时间.但是当我启动计时码表并更改方向以使其处于横向时,计时码表将重置并再次显示00:00.我希望它保留其价值. portraitlandscape的布局不同

I am building a simple timer app in which I am using android chronometer to track time passed. but when I start chronometer and change orientation to landscape the chronometer resets and and show 00:00 again. I want it to retain its value. layouts for portrait and landscape are different

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"/>

推荐答案

文档内容如下:

重新创建活动

Recreating an Activity

警告:每次用户旋转屏幕时,您的活动都会被破坏并重新创建.当屏幕改变方向时,由于屏幕配置已更改,并且您的活动可能需要加载替代资源(例如布局),因此系统会破坏并重新创建前台活动.

Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).

如果您需要保存活动的状态在更改方向之前,您必须覆盖onSaveInstanceState().此方法将帮助您保存方向更改后要恢复的所有值.然后使用onCreate()方法还原它们.

If you need to Save activity's state before changing orientation, you have to override onSaveInstanceState(). This method will help you save all the values you want to get back after orientation changes. Then restore them in onCreate() method.

String myVar;

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

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

Now retrieve it when creating the activity :

@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");
    }
    /*
       ...
    */
}

这篇关于如何通过方向更改包含Android计时码表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆