我目前正在尝试在我的应用程序中实现首选项片段,但在设置 setOnPreferenceClickListener 时遇到问题。似乎侦听器根本不工作,并且代码从未被实现。我现在只是在听众中放了一个 Toast 作为测试。我浏览了许多论坛,到目前为止还没有找到一个好的答案。代码如下。提前致谢!
SettingFragment.java
public class SettingsFragment extends PreferenceFragment {
private OnFragmentInteractionListener mListener;
private Preference mFontPreference;
private Preference mFontSizePreference;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.fragment_settings);
mFontPreference = findPreference("font_preference");
mFontSizePreference = findPreference("font_size_preference");
mFontPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
Toast.makeText(getActivity(), key, Toast.LENGTH_LONG).show();
return true;
}
});
}
片段设置.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent" >
<PreferenceCategory android:title="Text Settings">
<ListPreference
android:enabled="true"
android:key="font_preference"
android:title="Font"
android:summary="Select a Font"
android:entries="@array/font_spinner_array"
android:entryValues="@array/font_spinner_array"/>
<ListPreference
android:enabled="true"
android:key="font_size_preference"
android:title="Font Size"
android:summary="Select a Font Size"
android:entries="@array/font_size_array"
android:entryValues="@array/font_size_value_array"/>
</PreferenceCategory>
</PreferenceScreen>
数组.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="font_spinner_array">
<item>System Font</item>
<item>Helvetica</item>
<item>Helvetica-Neue</item>
<item>Impact</item>
</string-array>
<string-array name="font_size_array">
<item>Small</item>
<item>Medium</item>
<item>Large</item>
</string-array>
<string-array name="font_size_value_array">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
编辑: 所以 Toast 没有工作,因为它没有 .show()。已修复,单击时会显示“font_preference”。侦听器正在工作,但我想提取用户单击的条目的值,而不是整个首选项的键。有没有办法做到这一点?