使用统一首选项无法保留我的首选项

时间:2013-05-02 13:01:23

标签: android android-preferences

我使用this库来创建我的PreferenceActivity。到目前为止它工作得很好,但我不能在我的偏好设置上设置任何听众。

我的Activity看起来如何:

public class PrefActivity extends UnifiedSherlockPreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHeaderRes(R.xml.preference_headers);
        // Set desired preference file and mode (optional)
        setSharedPreferencesMode(Context.MODE_PRIVATE);

        super.onCreate(savedInstanceState);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Preference p = (Preference)findPreference("deleteSavedSearches");
        p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                        @Override
                        public boolean onPreferenceClick(Preference arg0) { 
                            //code for what you want it to do   
                            return true;
                        }
                    });
    }
}

这是我的PreferenceScreen:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <Preference
        android:key="deleteSavedSearches"
        android:summary="Gespeicherte Suchen löschen"
        android:title="Gespeicherte Suchen löschen" />

</PreferenceScreen>

这些是我的标题:

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:unified="http://schemas.android.com/apk/res-auto" >

    <!--
    /*
    ** Header definitions are identical to android:* except for preferenceRes which should be a reference to a preference xml file
    ** Unlike the native headers these are also used for building the single pane version.
    */
    -->
    <header
        unified:fragment="com.example.skelett.PrefActivity$GeneralPreferenceFragment"
        unified:preferenceRes="@xml/pref_country"
        unified:title="Land" />
    <header
        unified:fragment="com.example.skelett.PrefActivity$GeneralPreferenceFragment"
        unified:preferenceRes="@xml/pref_data"
        unified:title="Daten" />

</preference-headers>

在这种情况下,pnullgetPreferenceScreen()也始终返回null。我在偏好xml中设置了我的密钥。我错过了什么?

1 个答案:

答案 0 :(得分:0)

只需在onPostCreate中移动findPreference方法即可:

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    Preference p = (Preference) findPreference("deleteSavedSearches");
    p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // code for what you want it to do
            return true;
        }
    });
}