问题
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?
回答1:
findPreference()
should be called from a class implementing PreferenceActivity
interface (PreferencesActivity
in my context). MainActivity
properties can be accessed via SharedPreferences
class.
来源:https://stackoverflow.com/questions/9646247/android-how-do-i-call-findpreference-from-my-main-activity