因此,SettingsActivity 实现了一个 SettingsFragment。我正在学习 Udacity 类(class)。我的主要问题是,findPreference() 不起作用! 这是developer.android.com 网站上的内容:
查找首选项 添加到 API 级别 1 首选项 findPreference(CharSequence 键) 此方法在 API 级别 11 中已弃用。 此函数与现代基于 fragment 的 PreferenceActivity 无关。
那么,如何为 FRAGMENT 引入 listPreference? 如果我使用 PreferenceActivity,则此方法可以工作,但已被弃用。
package com.example.android.listview1;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.preference.*;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ListPopupWindow;
import java.util.prefs.PreferenceChangeListener;
public class SettingsActivity extends AppCompatActivity implements Preference.OnPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,new SettingsFragment()).commit();
**bindPreferenceSummaryToValue(findPreference());**
}
private void bindPreferenceSummaryToValue(Preference preference)
{
preference.setOnPreferenceChangeListener(this);
onPreferenceChange(preference,PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),"") );
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String value = newValue.toString();
//if the preference is an instance of ListPreference then you convert the preference object to ListPreference
if(preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
//return the index of the value that is selected
int prefIndex = listPreference.findIndexOfValue(value);
//if there's at least 1 item in the ListPreference, then you set the summary by getting the object at the index
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
else
preference.setSummary(value);
}
return true;
}
}
最佳答案
我知道如何解决这个问题了。将除 onCreate 之外的所有代码/方法移至 SettingsFragment。将bindPreferenceSummaryToValue(findPreference()) 也移至SettingsFragment 并摆脱onCreate() 的实现。
关于java - 如何更新列表首选项摘要(findPreference() 不起作用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38386299/