Yes or No confirmation in Android Preferences [duplicate]
Asked Answered
A

2

3

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.

Alexandretta answered 28/3, 2014 at 22:32 Comment(0)
D
7

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);
    }
}
Dacy answered 28/3, 2014 at 22:36 Comment(2)
I know how to use AlertDialog, what I don't understand is how to implement the DialogPreference subclass. What functions should I override?Alexandretta
Yes, I did something similar, thanks!Alexandretta
A
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"
        />
Alexandretta answered 28/3, 2014 at 23:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.