I'm getting a compiler error cannot resolve method findPreference when I try to intialize an OnSharedPreferencesChanged
listener in my MainActivity. According to the answer here:
findPreference() should be called from a class implementing PreferenceActivity interface
but I don't understand what the code to do this would be. How can I get rid of the compiler error and successfully set listeners for preference changes?
MainActivity.java
public class MainActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
//Test preference menu
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key); //COMPILER ERROR HERE
MainActivity.getGLSurfaceView().setTexture("");
// Set summary to be the user-description for the selected value
woodPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
findPreference
is a method which is part of bothPreferenceFragment
andPreferenceActivity
- these are the Fragments/Activities that actually show your Preference screen (the activity is deprecated and you should be using thePreferenceFragment
).You're trying to use it in your
MainActivity
. This doesn't work because the Preference objects don't actually exist on this screen (they exist in another activity that usually have aPreferenceFragment
as part of it). If you need to get access to a preference value of a preference in an activity that is not your preference screen, useSharedPreferences
, something like:You can check out the documentation for further examples.
If your
MainActivity
is supposed to be a screen that shows settings, then you should probably rename it and include a preference fragment inside of it.I believe you're also going to run into trouble with
setSummary
because thePreference
is not part of this activity, it's part of the activity where you actually modify the preferences.setSummary
is used to update the actual UI of thePreference
so that if you, for example, select one of three values when using a list preference, it shows the value you just selected on the screen.