Xiaosheng Wilson Wu Xiaosheng Wilson Wu - 5 months ago 30
Android Question

android preference screen inconvertible types

I am trying to create a preferenceScreen with this command

PreferenceScreen screen= (PreferenceScreen)getPreferenceScreen().findPreference(KEY);


and the error message is: "inconvertible types, cannot cast android.support.v7.preference.Preference to android.preference.preferenceScreen"

Is there a way to fix it? Thanks!

Update: this is part of the testing code I wrote

ArrayList<String> cmds = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
for (String cmd : cmds) {
CheckBoxPreference cpref = new CheckBoxPreference(getActivity().getApplicationContext());
cpref.setTitle(cmd);
cpref.setKey("The Name");
cpref.setChecked(true);
cmdScr.addPreference(cpref);
}


now the last line "addPreference" gives me an error

Answer

findPreference returns android.support.v7.preference.Preference and not the PreferenceScreen. What you need to do is this:

Preference screen = (Preference) getPreferenceManager().findPreference(KEY);

Where Preference is imported as the one from the support library:

import android.support.v7.preference.Preference;

To answer your edited question, just visit this link to see what you're doing wrong. Add the category to your screen, and then add the preference to the category.

Comments