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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 13:41:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!