簡體   English   中英

SharedPreferences不會在我的Android應用程序中保存復選框

[英]The SharedPreferences doesn't save the checked box in my Android app

我在AlertDialog中有一個復選框,該對話框在應用程序啟動時啟動。 我添加了“ SharedPreferences”以保存該復選框是否被選中。 如果選中此復選框,則AlertDialog將永遠不會啟動或在應用程序啟動時顯示。 但是我的問題是:選中該框時,每次啟動應用程序時,AlertDialog都會啟動。

checkbox.xml(布局文件):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:id="@+id/checkboxDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        style="?android:attr/textAppearanceMedium" />

</LinearLayout>

MainActivity.java中onCreate方法

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

        View checkBoxView = View.inflate(this, R.layout.checkbox, null);
        final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkboxDialog);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences prefs = getSharedPreferences("state", 0);

                if(prefs.getBoolean("x", false) == true)
                {
                    checkBox.setChecked(true);
                }
                else if(checkBox.isChecked() == true)
                {
                    SharedPreferences myPrefs = getSharedPreferences("state", 0);
                    SharedPreferences.Editor editor = myPrefs.edit();
                    editor.putBoolean("x", true);
                    editor.commit();
                }
            }
        });
        checkBox.setText("Test");
        final Context context = this;
        AlertDialog.Builder mainDialog = new AlertDialog.Builder(context);
        mainDialog.setTitle("Test");
        mainDialog.setMessage("Test my dialog!");
        mainDialog.setView(checkBoxView);
        mainDialog.setPositiveButton("Go to website", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                startActivity(browseIntent);
            }
        });
        AlertDialog alertDialog = mainDialog.create();
        alertDialog.show();

        ...
    }

我在這里找到了答案:

希望它能幫助別人。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM