我试图将EditTextPreference的值放入摘要中。有人能告诉我怎么做吗?它看起来像我的OnSharedPreferenceChangeListener无效。
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.util.Log;
public class OptionsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener{
private SharedPreferences sharedPreferences;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String s) {
// Adds preferences. See xml.preferences.
addPreferencesFromResource(R.xml.preferences);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("user_id")) {
Log.v("user_id", "is found");
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
我的偏好.xml:
<?xml version="1.0" encoding="utf-8"?><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBoxPreference
android:key="gps_sync"
android:title="@string/gps_sync"
android:summary="@string/gps_sync_summ"
android:defaultValue="true"/>
<EditTextPreference
android:key="user_id"
android:title="@string/user_id"
android:summary=" "/>
答案 0 :(得分:5)
您必须先注册监听器才能正常工作。
public class OptionsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key)
{
//Your Code
}