首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android -如何保存复选框状态,应用程序关闭后,保存在CheckBoxes中的值仍然存在?

Android -如何保存复选框状态,应用程序关闭后,保存在CheckBoxes中的值仍然存在?
EN

Stack Overflow用户
提问于 2020-01-22 18:02:53
回答 2查看 247关注 0票数 0

我一直在Android SDK平台上工作,并不清楚如何保存应用程序的状态。我正在创建一个包含CheckBoxes的菜单。我确实了解SharedPreferences的概念,但是我不能理解SharedPreferences在CheckBoxes中的实现。我希望这些复选框(多个复选框)保持选中/取消选中状态,即使用户重新启动应用程序也是如此。

代码语言:javascript
运行
复制
public class MainActivity extends AppCompatActivity {

    protected WebView myWebView;
    protected TextView text_selection;
    protected TextView mOutputText;
    public static final  String TAG = "mytag";
    protected SharedPreferences sharedPreferences;
    protected SharedPreferences.Editor editor;
    private final String PREFERENCE_FILE_KEY = "myAppPreference";
    private Context context;
    protected CheckBox animal, fisheries, dairy;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        animal = (CheckBox)findViewById(R.id.animal);
        fisheries = (CheckBox)findViewById(R.id.fisheries);
        dairy = (CheckBox)findViewById(R.id.dairy);

        //sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);


        //Context context = getActivity();
        //SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);


        editor = sharedPreferences.edit();
        editor.putBoolean("animal", false);
        editor.putBoolean("fisheries", false);
        editor.putBoolean("dairy", false);

        //editor.putBoolean("checkbox", checkbox.isChecked()));
        editor.commit();


        this.myWebView = (WebView) findViewById(R.id.webview);
        this.text_selection = findViewById(R.id.text_selected);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.setWebViewClient(new WebViewClient());
        myWebView.loadUrl("------");

        //mOutputText = (TextView) findViewById(R.id.tv_output);

        mOutputText = findViewById(R.id.textView);

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {

                        if(task.isSuccessful()){
                            String token=task.getResult().getToken();
                            Log.d(TAG, "onComplete: Token: "+token);
                            mOutputText.setText("Token has been generated");
                        }else{
                            mOutputText.setText("Token failed");
                        }

                    }
                });


    }



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

        if (sharedPreferences.getBoolean("animal", false)) {
            // findItem id function return the id of the menu
            menu.findItem(R.id.animal).setChecked(true);
        } else if (sharedPreferences.getBoolean("fisheries", false)) {
            menu.findItem(R.id.fisheries).setChecked(true);
        } else if (sharedPreferences.getBoolean("dairy", false)) {
            menu.findItem(R.id.dairy).setChecked(true);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){

        editor = sharedPreferences.edit();
        switch (item.getItemId()) {
            case R.id.animal:
                if (item.isChecked()) {

                    item.setChecked(false);
                    editor.putBoolean("animal", false);
                } else {
                    item.setChecked(true);
                    editor.putBoolean("animal", true);
                }
                break;
            case R.id.fisheries:
                if (item.isChecked()) {
                    item.setChecked(false);

                    editor.putBoolean("fisheries", false);
                } else {
                    item.setChecked(true);
                    editor.putBoolean("fisheries", true);
                }
                break;
            case R.id.dairy:
                if (item.isChecked()) {
                    item.setChecked(false);
                    editor.putBoolean("dairy", false);
                } else {
                    item.setChecked(true);
                    editor.putBoolean("dairy", true);
                }
                break;

        }


        editor.commit();
        return super.onOptionsItemSelected(item);



    }

}
EN

Stack Overflow用户

发布于 2020-01-22 18:09:58

onCreate中的开头部分替换为以下内容:

代码语言:javascript
运行
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);

    animal = (CheckBox)findViewById(R.id.animal);
    fisheries = (CheckBox)findViewById(R.id.fisheries);
    dairy = (CheckBox)findViewById(R.id.dairy);

    animal.setChecked(getCheckboxStatus("animal"));
    animal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              saveCheckBoxValue("animal", isChecked);
          }
      }
    );

    fisheries.setChecked(getCheckboxStatus("fisheries"));
    fisheries.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              saveCheckBoxValue("fisheries", isChecked);
          }
      }
    );

    dairy.setChecked(getCheckboxStatus("dairy"));
    dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              saveCheckBoxValue("dairy", isChecked);
          }
      }
    );

    // Your WebView and Firebase stuff
}

private void saveCheckBoxValue(String key, boolean isChecked) {
    editor = sharedPreferences.edit();
    editor.putBoolean(key, isChecked);
    editor.apply();
}

private boolean getCheckboxStatus(String key) {
    return sharedPreferences.getBoolean(key, false);
}

onCreateOptionsMenu函数更改为以下内容:

代码语言:javascript
运行
复制
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_menu, menu);
    menu.findItem(R.id.animal).setChecked(sharedPreferences.getBoolean("animal", false));
    menu.findItem(R.id.fisheries).setChecked(sharedPreferences.getBoolean("fisheries", false));
    menu.findItem(R.id.dairy).setChecked(sharedPreferences.getBoolean("dairy", false));
    return true;
}

onOptionsItemSelected函数更改为:

代码语言:javascript
运行
复制
@Override
public boolean onOptionsItemSelected(MenuItem item){
    editor = sharedPreferences.edit();
    switch (item.getItemId()) {
        case R.id.animal:
            editor.putBoolean("animal", item.isChecked());
            break;
        case R.id.fisheries:
            editor.putBoolean("fisheries", item.isChecked());
            break;
        case R.id.dairy:
            editor.putBoolean("dairy", item.isChecked());
            break;
    }
    editor.apply();
    return super.onOptionsItemSelected(item);
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59857062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档