安卓偏好设置中的“是”或“否”确认

3
我需要在设置中实现“重置”选项。当单击该设置时,应打开一个简单的对话框询问确认。
我已经查看了DialogPreference,但似乎找不到一个好的解决方案或教程。请有经验的人给我帮忙。我是初学者,任何想法甚至代码都将非常有帮助,谢谢。
2个回答

7

请检查此链接,使用AlertDialog.Builder,非常容易实现。

http://developer.android.com/guide/topics/ui/dialogs.html

或者使用DialogPreference...

将此添加到首选项 xml 中

  <com.examples.app.CustomDialogPreference
    android:title="Title"
    android:dialogMessage="Message"
    android:positiveButtonText="Yes"
    android:negativeButtonText="No"/>

在你的代码中,创建一个自定义对话框。这可能有些奇怪,但你必须这样做。

public class CustomDialogPreference  extends DialogPreference{
   public CustomDialogPreference(Context oContext, AttributeSet attrs){
     super(oContext, attrs);
    }
}

我知道如何使用AlertDialog,但我不明白如何实现DialogPreference子类。我应该重写哪些函数? - Vedavyas Bhat
1
请提供更新后的答案,我会尽快为您翻译。 - Libin
是的,我做了类似的事情,谢谢! - Vedavyas Bhat

7
我用了一个简单的解决方案,它有效,尽管我不知道这是否是最佳的方式。
YesNo类:
package com.me.myapp;
public class YesNo extends DialogPreference  
{ 
    public YesNo(Context context, AttributeSet attrs)   
    {  
        super(context, attrs);
    }

    @Override
    protected void onClick()
    {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle("Reset application?");
        dialog.setMessage("This action will delete all your data. Are you sure you want to continue?");
        dialog.setCancelable(true);
        dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() 
        {
            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                //reset database
                Toast.makeText(getContext(), "Application reset!", Toast.LENGTH_SHORT).show();
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        {
            @Override
            public void onClick(DialogInterface dlg, int which) 
            {
                dlg.cancel();
            }
        });

        AlertDialog al = dialog.create();
        al.show();
    }
}

在XML文件中的偏好设置:

<com.me.myapp.YesNo
        android:title="Reset application"
        android:summary="Delete all data"
        />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接