实例状态以保持按钮可见性

时间:2016-12-13 10:42:33

标签: android android-intent

如何从其他活动返回时保持按钮可见性?

我的代码:

@Override
protected void onStop() {
        super.onStop();

        SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
        SharedPreferences.Editor edit = btVis.edit();
        edit.putString("btS1",btSub1.getVisibility()+"");
    }

    @Override
    protected void onResume() {
        super.onResume();

        SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
        int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
        btSub1.setVisibility(btS1);    
    }

我收到错误原因setVisibility需要格式为View.(VISIBILITY)。但是我将btS1解析为格式为int的{​​{1}},所以我不知道为什么它不起作用。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你忘了打电话给editor.commit();,这意味着你的int实际上从未被保存过。

@Override
protected void onStop() {
    super.onStop();

    SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
    SharedPreferences.Editor edit = btVis.edit();
    edit.putString("btS1",btSub1.getVisibility()+"");
    editor.commit();
}

编辑:

我看到你也做错了什么

int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));

虽然您通过课程View获得了ID,但您不需要通过这种方式从共享首选项中获取该ID。您刚刚存储了View.GONE和View.Visisble中引用的Integer

要完成这项工作,您只需要:

int btS1 = Integer.parseInt(btVis.getString("btS1",""));

但我不明白为什么要将其解析为String,然后将其解析回int。另外,我会在OnPause而不是OnStop上进行保存。如此完全重做你应该这样做:

@Override
protected void onPause() {
    super.onPause();

    SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
    SharedPreferences.Editor edit = btVis.edit();
    edit.putInt("btS1", btSub1.getVisibility());
    edit.commit();
}

@Override
protected void onResume() {
    super.onResume();

    SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
    int btS1 = btVis.getInt("btS1", 0);
    btSub1.setVisibility(btS1);    
}

答案 1 :(得分:0)

在onResume()方法中尝试这个。

@Override
protected void onResume() {
    super.onResume();

    SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
    int visibility = Integer.parseInt(btVis.getString("btS1",""));
    switch(visibility){
    case View.VISIBLE: //make button visible
    break;
    case View.INVISIBLE: //make button invisible
    break;
    }

}

确保在onStop()方法结束时提交编辑器