其他分享
首页 > 其他分享> > android – 首选项上的首选项活动单击“侦听器”

android – 首选项上的首选项活动单击“侦听器”

作者:互联网

我正在构建一个Preference Activity,其中列表中的大多数首选项将执行代码而不直接修改SharedPreference.我的preferences.xml文件看起来像这样.

<PreferenceCategory
    android:title="Connection" >

    <Preference
        android:id="@+id/settings_connectToNewComputer"
        android:key="connectToNewComputer"
        android:summary="Currently connected to:"
        android:title="Connect to new computer" />

    <Preference
        android:id="@+id/removeDevice"
        android:key="removeDevice"
        android:summary="Remove this device from the computer's whitelist"
        android:title="Remove this device from computer" />

</PreferenceCategory>

<PreferenceCategory
    android:title="About" >

    <Preference
        android:id="@+id/settings_About"
        android:key="about"
        android:summary="About me and my thanks to those who made this app great"
        android:title="About Hue Pro" />

    <Preference
        android:id="@+id/contact"
        android:key="contact"
        android:summary="Contact me with comments, bugs, and suggestions for updates"
        android:title="Contact me" />

</PreferenceCategory>

我的目标是在单击其中一个首选项时执行一段代码.与Google Play设置首选项菜单中的“清除搜索记录”类似. (http://i.imgur.com/qnHbJX9.png)

有谁知道如何使这成为可能?

我必须补充一点,我尝试使用findPreference(“KeyNameHere”),但它总是返回null.

谢谢!

编辑:

我在此代码中添加并实现了OnPreferenceClickListener:

@Override
public boolean onPreferenceClick(Preference preference) {
    return false;
}

但这种方法永远不会被调用.还有另一种方法吗?

编辑2:

我发现如果我取出PreferenceCategory标签,所以我留下了这个:

<Preference
    android:id="@+id/settings_connectToNewComputer"
    android:key="connectToNewComputer"
    android:summary="Currently connected to:"
    android:title="Connect to new computer" />

<Preference
    android:id="@+id/removeDevice"
    android:key="removeDevice"
    android:summary="Remove this device from the computer's whitelist"
    android:title="Remove this device from computer" />

<Preference
    android:id="@+id/settings_About"
    android:key="about"
    android:summary="About me and my thanks to those who made this app great"
    android:title="About Hue Pro" />

<Preference
    android:id="@+id/contact"
    android:key="contact"
    android:summary="Contact me with comments, bugs, and suggestions for updates"
    android:title="Contact me" />

并称之为:

getPreferenceScreen().setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            return false;
        }
    });

然后我实际上从click事件中得到了响应.唯一的缺点是我必须删除首选项分组.任何人都知道为什么这是和任何方法来解决它?

解决方法:

实现OnPreferenceClickListener并在onPreferenceClick中

@Override
public boolean onPreferenceClick (Preference preference)
{
    String key = preference.getKey();
    // do what ever you want with this key
}

标签:preferenceactivity,android,onclicklistener
来源: https://codeday.me/bug/20191001/1838714.html