android - 从 PreferenceScreen 到 DialogPreference

标签 android

我的应用程序有一个设置菜单,它实际上是一个 PreferenceActivity。 创建时,如果未设置 bool 值,我想转到设置该值的 DialogPreference。

我尝试这样做是有意的,但应用程序强制关闭并出现此错误消息:

E/AndroidRuntime( 239): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.xxxx/com.xxxx.xxxxPreference}; have you declared this activity in your AndroidManifest.xml?

我应该怎么做?可以将该 DialogPreference 添加到 list 中吗?

最佳答案

DialogPreference 本身并不是一个Activity。它只是一个 Preference,在单击时显示一个 Dialog

问题是没有明显的方法以编程方式单击Preference。但是,由于您使用的是 DialogPreference,因此您已经拥有了它自己的子类。因此,我们可以通过将以下方法添加到 DialogPreference 的子类中来解决我们的问题:

//Expose the protected onClick method
void show() {
    onClick();
}

然后在 PreferencesActivityonCreate() 中,您将有类似这样的东西从您的 XML 文件加载首选项:

// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);

之后你可以像这样输入一些代码:

booleanProp = true; //set this to the value of the property you're checking     

if (! booleanProp) {
    //Find the Preference via its android:key
    //MyDialogPreference is your subclasss of DialogPreference
    MyDialogPreference dp = (MyDialogPreference)getPreferenceScreen().findPreference("dialog_preference");  
    dp.show();
}

这有点 hack,因为公开 protected 方法并不理想,但它确实有效。

另一种选择是将 Dialog 替换为 PrefenceActivity,其中包含您希望维护的所有选项,然后您可以通过 Intent< 启动它,但我假设您有充分的理由想要自己的具有特定布局的自定义 Dialog。如果您确实想要第二个 PreferenceActivity,您可以将其添加到您的首选项 XML 文件中,如下所示:

<PreferenceScreen
        android:title="@string/title_of_preference"
        android:summary="@string/summary_of_preference">
    <intent android:action="your.action.goes.HERE"/>
</PreferenceScreen>

关于android - 从 PreferenceScreen 到 DialogPreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2164729/

相关文章:

javascript - map 拖动事件 谷歌地图 android sdk cordova cordova-plugin-googlemaps

android - 无法通过 ID 或标签找到 fragment ......但它在那里

android - 当该按钮上的选项卡(选中)时更改颜色并获得其他按钮的正常布局

java - 日历 View Android 帮助

android - 有没有办法在android中显示一个全局对话框?

android - 房间迁移根据现有的值添加列

android - Android Kitkat中蓝牙HID设备配置文件的实现

c# - Xamarin - TabbedPage 导航错误(页面不能有 parent )

android - 将 json 文件导入到 firebase 中的实时数据库的替代方法

android - 如何在 flutter 中使用 chrome 自定义标签页