如何以编程方式打开或模拟使用 XML 创建的 Android 首选项上的单击? [英] How to open or simulate a click on an android Preference, created with XML, programmatically?

查看:29
本文介绍了如何以编程方式打开或模拟使用 XML 创建的 Android 首选项上的单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 XML 中声明首选项的 android 应用程序,加载了 addPreferencesFromResource.用户可以打开首选项,点击每个项目并进行编辑,一切正常.

I've an android application with preferences declared in XML, loaded with addPreferencesFromResource. The user can open preferences, click on each item and edit them, all works.

我的一个偏好是:

        <ListPreference android:key="abc"
            android:title="@string/abc"
            android:summary="@string/cde"
            android:persistent="true"/>

如何自动向用户显示首选项对话框(无需用户转到首选项屏幕并单击它?).

How can I show the preference dialog to a user automatically (without the need for the user to go to the preference screen and click on it?).

我尝试了 ( (android.preference.DialogPreference) prefMgr.findPreference( "abc" )).showDialog(null),但据说它是一个受保护的方法......?从我的主要活动(这是一个 PreferenceActivity)调用它,这就是它显然无法工作的原因.不然怎么办?

I tried ( (android.preference.DialogPreference) prefMgr.findPreference( "abc" )).showDialog(null), but is says it is a protected method...? Called it from my main activity (which is a PreferenceActivity), that's why it obviously cannot work. But how else?

编辑

我刚刚找到了两个线程(12) 的想法是使用 findViewById 访问首选项,但没有成功.它总是返回 null(对我也是如此).

I just found two threads (1, and 2) with the idea to use findViewById to access the preference, but with no success. It always returns null (does for me, too).

看起来真的不可能从代码中做到这一点.

It looks like there is really no possibility to do this from code.

推荐答案

您可以扩展 ListPreference 来创建对话框,然后包含您自己的公共方法,该方法调用 ListPreference 的受保护的 showDialog 方法.类似的东西:

You could have extended ListPreference to create your dialog, then included your own public method that calls the protected showDialog method of ListPreference. Something like:

public void show()
{
    showDialog(null);
}

这样,当有 PreferenceGroups 时,您就不会遇到 getOrder() 不起作用的问题,正如一些人在您的回答的评论中指出的那样.

This way you won't run into the issue of getOrder() not working when there are PreferenceGroups as several people have pointed out in the comments your answer.

这可以通过任何具有受保护的 showDialog 方法的首选项类型来完成.

This can be done with any preference types that has a protected showDialog method.

这篇关于如何以编程方式打开或模拟使用 XML 创建的 Android 首选项上的单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆