2016-04-16 67 views

回答

0

我相信你正在尋找一個回調的接口定義被點擊的偏好時要調用:

Preference.OnPreferenceClickListener

+0

如此接近,它是[OnPreferenceChangeListener](http://developer.android.com/reference/android/support/v7/preference/Preference.OnPreferenceChangeListener.html)。 –

0

我找到了另一種方式來訂閱所有喜好的所有變化:SharedPreferences.OnSharedPreferencesChangeListener。具有兩個替代方案的代碼如下所示:

import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.preference.Preference; 
import android.support.v7.preference.PreferenceFragmentCompat; 
import android.util.Log; 


/** 
* A simple {@link Fragment} subclass. 
*/ 
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener { 


    private static final String TAG = "SettingsFragment"; 

    private Preference thePreference; 

    public SettingsFragment() { 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     addPreferencesFromResource(R.xml.pref); 

     thePreference = findPreference("chosen_theme"); 

     if (thePreference != null) { 
      thePreference.setOnPreferenceChangeListener(this); 
     } else { 
      Log.d(TAG, "Preference is empty"); 
     } 
    } 

    @Override 
    public void onCreatePreferences(Bundle bundle, String s) { 


    } 

    @Override 
    public boolean onPreferenceChange(Preference preference, Object o) { 

     Log.d(TAG, String.format("Changed: %s", preference.getKey())); 

     return true; 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 

     getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 

     getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); 
    } 

    @Override 
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 

     Log.d(TAG, String.format("%s %s", sharedPreferences, key)); 
    } 
} 

SharedPreferences速度更快,首選項更加靈活。

相關問題