Search code examples
androidpreferences

Android: how do I call findPreference() from my main activity?


I'm handling the preferences screen for my Android app. I want to disable (grey it out) an item if the preceding one has a specific value.

I have implemented two classes: MainActivity and PreferencesActivity.

In MainActivity I do:

public class MainActivity extends Activity implements OnSharedPreferenceChangeListener {
...
    public void onCreate (Bundle savedInstanceState) {
        ...
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPrefs.registerOnSharedPreferenceChangeListener(this);
        ...
    }

Then, when my preferences are requested by the user:

startActivity(new Intent(this, PreferencesActivity.class));

Then, to handle preferences in MainActivity, I do:

@Override
public void onSharedPreferenceChanged (SharedPreferences prefs, String key) {
    if ("sport".equals(key)) {
        sport = prefs.getString("sport", "");
        ListPreference lp = findPreference("match_duration");
        if (sport.equals(getString(R.string."sport_soccer"))) {
            lp.setEnabled(false);
        }
    }
    ...
 }

The problem is I can't call findPreference in MainActivity ("The method findPreference(String) is undefined for the type MainActivity"...). Is my approach wrong? Shoud I implement onSharedPreferenceChanged() method in PreferencesActivity? If so, how do I use MainActivity properties in PreferencesActivity?


Solution

  • findPreference() should be called from a class implementing PreferenceActivity interface (PreferencesActivity in my context). MainActivity properties can be accessed via SharedPreferences class.