简体   繁体   中英

PreferenceFragmentCompat not recognizing Preference Changes

I am attempting to put the value of an EditTextPreference into the summary. Can someone show me how to do this? It doesn't seem like my OnSharedPreferenceChangeListener is working.

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, ""));
        }
    }
}

My preferences.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=" "/>

You have to first register the listener for it to work.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM