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

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

问题描述

我有一个使用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?

编辑

我刚刚发现了两个线程( 1 2 ),并希望使用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 Preference的点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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