如何实现确认(是/否)DialogPreference?

sh1*_*1ng 97 android confirmation android-preferences dialog-preference

如何实现显示简单是/否确认对话框的首选项?

有关示例,请参阅Browser->Setting->Clear Cache.

Maa*_*lte 269

这是一个简单的警报对话框,Federico为您提供了一个可以查找的网站.

以下是如何构建警报对话框的简短示例.

new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int whichButton) {
        Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
    }})
 .setNegativeButton(android.R.string.no, null).show();
Run Code Online (Sandbox Code Playgroud)

  • 我知道如何建立一个Dialog,但我的q关于偏好. (3认同)

Xåp*_* - 9

Android附带了一个内置的YesNoPreference类,可以完全按照您的需要执行(带有yes和no选项的确认对话框).请在此处查看官方源代码.

不幸的是,它在com.android.internal.preference软件包中,这意味着它是Android私有API的一部分,您无法从您的应用程序访问它(私有API类可能会更改,恕不另行通知,因此Google不允许您访问它们).

解决方案:只需从我提供的链接中复制/粘贴官方源代码,即可在应用程序包中重新创建类.我试过这个,它运行正常(没有理由不这样做).

然后,您可以将其添加到您的preferences.xml任何其他首选项.例:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

截图