Yes or No confirmation in Android Preferences [duplicate]

笑着哭i 提交于 2020-01-05 03:25:33

问题


I need to implement a "Reset" option in Settings. When the setting is clicked, a simple dialog should open asking to confirm.

I've taken a look at DialogPreference but I can't seem to be able to find a good solution, or tutorials anywhere. Can someone please help me out? I'm a beginner, ideas or even code would be very helpful, thank you.


回答1:


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"
        />



回答2:


Check this link . use AlertDialog.Builder , Its very easy to do

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

else using DialogPreference ..

Add this to preference xml

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

In your code, create a custom Dialog. This is weird, but you have to

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


来源:https://stackoverflow.com/questions/22724301/yes-or-no-confirmation-in-android-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!