首先 - 我已经尝试了所有可以在stackoverflow上找到的帖子,但没有一个能为我解决。
我正在使用begginners指南来创建一个简单的应用程序 - 因此所有的评论。
我的问题是,每当我尝试将首选项附加到“this”时,侦听器(我已将我的类实现为侦听器:settings activity实现了Preference.OnPreferenceChangeListener),我的应用程序将崩溃!
我正在尝试将每个偏好的关键字作为摘要。
请帮助我 - 我已尝试过每一个相关结果并没有帮助。非常感谢!
这是我的设置活动类
公共类SettingsActivity扩展了PreferenceActivity 实现Preference.OnPreferenceChangeListener {
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add 'general' preferences, defined in the XML file FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment1 fragment1 = new Fragment1(); ft.replace(android.R.id.content, fragment1); ft.commit(); // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be // updated when the preference changes. **Here I need to somehow attach the preferences to the listener - but I can't seem to do it without the app crashing** } /** * Attaches a listener so the summary is always updated with the preference value. * Also fires the listener once, to initialize the summary (so it shows up before the value * is changed.) */ private void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. //preference.setOnPreferenceChangeListener(this); // Trigger the listener immediately with the preference's // current value. onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list (since they have separate labels/values). ListPreference listPreference = (ListPreference) preference; int prefIndex = listPreference.findIndexOfValue(stringValue); if (prefIndex >= 0) { preference.setSummary(listPreference.getEntries()[prefIndex]); } } else { // For other preferences, set the summary to the value's simple string representation. preference.setSummary(stringValue); } return true; }
}
答案 0 :(得分:0)
如果要将当前首选项值设置为摘要,只需添加您的preference.xml
android:summary="%s"
现在你不听听了
答案 1 :(得分:0)
您必须在onResume()和onPause()中执行此操作,如本文档所述:http://developer.android.com/guide/topics/ui/settings.html
只需在其中搜索onResume。
答案 2 :(得分:0)
我在我的应用程序中使用它,并且没有问题
试一试,也许有效
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//....... Code
}