3

我需要在“设置”中实现“重置”选项。单击设置时,应打开一个简单的对话框,要求确认。

我已经看过了,DialogPreference但我似乎无法在任何地方找到一个好的解决方案或教程。有人可以帮我吗?我是初学者,想法甚至代码都会非常有帮助,谢谢。

4

2 回答 2

7

I used a simple solution and it works, although I don't know if that's the best way to do it.

YesNo class:

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();
    }
}

and the preference in the XML file:

<com.me.myapp.YesNo
        android:title="Reset application"
        android:summary="Delete all data"
        />
于 2014-03-28T23:03:45.323 回答
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);
    }
}
于 2014-03-28T22:36:09.920 回答