从不同的视图、不同的值调用相同的 PreferenceActivity

Call same PreferenceActivity from different Views, different values

假设我有 10 个 ID 为 1,2,...,10 的按钮。我有一个名为 preferences.xml 的 XML 文件,其中包含一个复选框:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="applicationPreference" android:title="@string/config">
   <CheckBoxPreference
        android:key="checkbox" />                  
</PreferenceScreen>

我的按钮都调用相同的函数,该函数调用 Intent 以启动 PreferenceActivity。

我想要做的是用每个按钮调用相同的模型,但保存每个按钮的复选框的值。目前,每次我点击一个按钮,它都会启动 activity,但是,例如,我的按钮 1 的值将在我的按钮 5 的值中找到。

我应该使用 SharedPreferences 还是其他?

我知道这是可能的,但由于我对很多概念还不熟悉,所以我就是找不到。

如果我没理解错的话,你必须告诉 PreferenceActivity 按下了哪个按钮。您可以通过在启动 activity.

时将按钮 ID 设置为参数来实现此目的
/*
 * This is the common method used by all the buttons after the click 
 * was done in order to start the PreferenceActivity and pass
 * the button id as a parameter
 * @param sender - Button which was pressed and will start the
 * PreferenceActivity
*/
private void startPreferenceActivity(Button sender)
{
    // create the intent
    Intent intent=new Intent(context, PreferenceActivity.class);

    // add button id as a parameter
    intent.putExtra("buttonID", sender.getId());

    // start activity
    startActivity(intent);

    // or you can start it to way for a result 
    // startActivityForResult(intent, 0);
}

现在,在 PreferenceActivity 中你必须得到你发送的参数:

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the extras where the parametrs are stored
    Bundle bundle = getIntent().getExtras();

    if(bundle.getInt("buttonID") != null)
    {
            // get id as int with default value as 0
            int id= intent.getInt("buttonID", 0);
    }

    if(bundle.getString("buttonID") != null)
    {
            // get id as string with default value as ""
            string id= intent.getString("buttonID", "");
    }

    // other code here ...

}

希望对您有所帮助。

这是您的问题:PreferenceActivity 会自动为您在应用程序的共享首选项中保存设置。对于每个设置,您在 preferences.xml 中定义一个键。在你的情况下,这是

android:key="checkbox"

因此,当您使用按钮 5 打开首选项时,SP 中的值 "checkbox" 会设置为 true。当您再次使用按钮 1 打开首选项时, PreferencesActivity 查找 SP,发现 "checkbox" 是 true,因此将复选框设置为 checked.

要避免此问题,如 Adrian 所说,您必须将有关单击哪个按钮的信息传递给 PreferenceActivity。在您的 PreferenceActivity 中,您必须获得对您​​的复选框首选项的引用,并将您传递的按钮 ID 添加到键中。

Preference checkboxPreference = findPreference("checkbox");
checkboxPreference.setKey(checkboxPreference.getKey() + buttonId);

现在您的每个按钮都有 10 个唯一命名的布尔值("checkbox1"、"checkbox2"、..)保存在您的 SP 中。

玩得开心