保存按钮onSaveInstanceState的状态

时间:2014-11-11 18:18:41

标签: android button

好的,这个对我来说真的很棘手。这个想法是EMS的时间日志。您通过所采取的操作按下按钮,并记录下次使用的时间。我设法弄清楚如何将TextView保存为字符串。现在,我如何保存logTime1.setEnabled(false);所以在轮换或离开活动时,它会恢复它被禁用?最后我会在它旁边有另一个按钮,允许你编辑解锁按钮。这是代码。

公共类TimeLog扩展了Activity {

boolean logTimeDis1=true;
Button logTime1;
String time1;
TextView ivTimeStamp;
int counter=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.time_log);
    logTime1 = (Button) findViewById(R.id.logTime1);
    ivTimeStamp = (TextView) findViewById(R.id.ivTimeStamp);
    if(savedInstanceState != null) logTime1.setEnabled(savedInstanceState.getBoolean("logTimeDis1", true));
    logTime1.setOnLongClickListener(new View.OnLongClickListener() {


        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            time1 = new SimpleDateFormat("HH:mm", Locale.US).format(new Date());

            ivTimeStamp.setText(time1);
            logTime1.setEnabled(false);
            logTimeDis1 = false;
            return false;
        }
    });
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    counter++;
}


@Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
    outState.putString("ivTimeStamp", ivTimeStamp.getText().toString());
    outState.putBoolean("logTimeDis1", logTimeDis1);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onRestoreInstanceState(savedInstanceState);
    ivTimeStamp.setText(savedInstanceState.getString("ivTimeStamp"));
}




}

1 个答案:

答案 0 :(得分:0)

所以,在这一行

if(savedInstanceState != null) logTime1.setEnabled(savedInstanceState.getBoolean("logTmeDis1", false));

您不检查savedInstanceState是否包含logTmeDis1。比如说,savedInstanceState不是null,但是没有logTmeDis1,你将得到false并且你的按钮被锁定了。实际上,在这种情况下你不必检查它,只需将false改为true,它应该可以正常工作。