1

我使用这个库来创建我的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 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 中设置了我的密钥。我错过了什么?

4

1 回答 1

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;
        }
    });
}
于 2013-08-14T10:34:24.070 回答