Android Preference在代码中始终为NULL

时间:2015-11-24 13:29:41

标签: java android

我想用{DB}填充MultiSelectListPreference。当我打电话

MultiSelectListPreference list = (MultiSelectListPreference)findPreference("my_list_key");

在我的SettingActivity OnCreate方法中,我始终null。为什么呢?

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <MultiSelectListPreference
            android:key="my_list_key"
            android:title="My List"
            android:defaultValue="@array/default_array" />
</PreferenceScreen>

修改

这是完整的相关代码

public class SettingsActivity extends AppCompatPreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
        initPreferences();
    }

    private void initPreferences() {        
        MultiSelectListPreference list = (MultiSelectListPreference)findPreference("my_list_key");
    }        

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class GeneralPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_general);
            setHasOptionsMenu(true);
            bindPreferenceSummaryToValue(findPreference("my_list_key"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
              //....
        }
    }
}

pref_headers.xml

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
    <header android:fragment="MyApp.SettingsActivity$GeneralPreferenceFragment"
        android:id="@+id/gen_pref_id"
        android:title="General"
        android:icon="@drawable/ic_info_black_24dp" />
   </header>
</preference-headers>

0 个答案:

没有答案