onPreferenceClick and OnPreferenceClickListener

前端 未结 2 607
我寻月下人不归
我寻月下人不归 2021-01-21 16:19

I\'m attempting to evaluate my preferences in my java code in order to enable/disable other options it they chose not to do other options... So far i\'m trying to only implement

相关标签:
2条回答
  • 2021-01-21 16:37

    first implement "OnSharedPreferenceChangeListener"

    PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
    

    Then

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        settings.registerOnSharedPreferenceChangeListener(this);
    
    }
    

    THEN

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    
        switch (key) {
            case "pref_key_auto_delete":
                boolean notificationStatus = SP.getBoolean(key, false);
                Log.d("stat", String.valueOf(notificationStatus));
                break;
    
            case "pref_key_notification_list":
                String downloadType = SP.getString(key, "n/a");
                Log.d("stat", String.valueOf(downloadType));
                break;
        }
    
    0 讨论(0)
  • 2021-01-21 16:51

    You have to register for PreferenceClickListener each individual preference

    somePreference.setOnPreferenceClickListener(this);  
    

    or you can use getSharedPreferences().registerOnSharedPreferenceChangeListener for all preferences.

    public class UserSettingActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
    SharedPreferences mPreferences;
    Boolean frequency;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
    
    @SuppressWarnings("deprecation")
    @Override
    protected void onPause()
    {
        super.onPause();
    
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }
    
    @SuppressWarnings("deprecation")
    @Override
    protected void onResume()
    {
        super.onResume();
    
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }
    
    
    @SuppressWarnings("deprecation")
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("schedulestop")) {
             // do something
         }
         else if (key.equals(......
    }
    }
    
    0 讨论(0)
提交回复
热议问题