gpt4 book ai didi

android - PreferenceFragmentCompat 无法识别首选项更改

转载 作者:太空狗 更新时间:2023-10-29 16:00:01 26 4
gpt4 key购买 nike

我正在尝试将 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, ""));
}
}
}

我的 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=" "/>

最佳答案

你必须先注册监听器才能工作。

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
}

关于android - PreferenceFragmentCompat 无法识别首选项更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38599422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com