0

一旦我关闭模拟器然后再次运行它,我就无法保存按钮的状态。这是 onCreate 和 onDestory 中的代码

@Override
protected void onDestroy() {

    super.onDestroy();
    ViewGroup v=(ViewGroup) findViewById(R.id.GridLayout1);

    SharedPreferences setting= getSharedPreferences("MyPrefs",0);
    SharedPreferences.Editor editor=setting.edit();
    for(int i=2; i < ((ViewGroup)v).getChildCount(); i++) {
        View childView = ((ViewGroup)v).getChildAt(i);
        int resID = childView.getId();
        Button btn = (Button) findViewById(resID);
        editor.putString("value",btn.getText().toString());
        editor.commit();
    }
}
4

1 回答 1

3

你是对的。

valueonDestroy.

    for(int i=2; i < ((ViewGroup)v).getChildCount(); i++) {
        View childView = ((ViewGroup)v).getChildAt(i);
        int resID = childView.getId();
        Button btn = (Button) findViewById(resID);
        editor.putString("value",btn.getText().toString());
        editor.commit();
    }

您必须使用唯一键存储每个值,每个值对应一个唯一按钮,然后在onCreate.

要选择您的唯一键,我建议使用按钮的 ID。

    for(int i=2; i < ((ViewGroup)v).getChildCount(); i++) {
        View childView = ((ViewGroup)v).getChildAt(i);
        int resID = childView.getId();
        Button btn = (Button) findViewById(resID);
        editor.putString(String.valueOf(btn.getId()),btn.getText().toString());
        editor.commit();
    }
于 2013-10-13T01:43:34.230 回答