0

当我尝试将 a 保存boolean到 a时,它似乎已保存(来自打印输出),但是在从访问应用程序的设置页面返回后,系统在重新创建过程Bundle中没有调用该方法。onRestoreInstanceState(设置在单独的活动中,从右上角的选项列表中点击)
根据:
https
://developer.android.com/training/basics/activity-lifecycle/recreating.html 该onRestoreInstanceState方法将仅在Bundle!=时调用null
我还将它放入onCreate方法中(使用空检查器)并且Bundle总是出现空值。
我没有足够的声誉来发布图片,但这个链接显示了 logcat:https://www.dropbox.com/s/v6vw9ynw5az5zhg/AndroidLogCat.PNG?dl=0

public class MyActivity extends AppCompatActivity {
    public final static String SWITCH_NAME = "com.company.name.myactivity.SWITCH";

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        System.out.println("RESTORING INSTANCE STATE");
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            System.out.println("RECEIVED INSTANCE STATE");
        }
        System.out.println("test");
        super.onCreate(savedInstanceState);
        System.out.println("TEST");
        setContentView(R.layout.activity_my);
        System.out.println("TeSt");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_my, menu);
        return true;
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        System.out.println("SAVING STEP 1: " + getSwitchValue());

        savedInstanceState.putBoolean(SWITCH_NAME, getSwitchValue());
        System.out.println("SAVING TEST BEFORE SUPERCLASS: " + savedInstanceState.getBoolean(SWITCH_NAME));

        super.onSaveInstanceState(savedInstanceState);
        System.out.println("SAVING TEST AFTER SUPERCLASS: " + savedInstanceState.getBoolean(SWITCH_NAME));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            Intent intent = new Intent(this, DisplayMessageActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private boolean getSwitchValue() {
        boolean switchValue = true;

        Switch aSwitch = (Switch) findViewById(R.id.switch1);
        if (aSwitch != null) switchValue = aSwitch.isChecked();

        return switchValue;
    }
}

谢谢!
罗比

4

0 回答 0