Question

I'm trying to write something to set a password with DialogPrefence. How do I get the onClick() event at OK button from the dialog?

Here is the code:

package com.kontrol.app;

import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;

public class SS1_Senha extends DialogPreference implements DialogInterface.OnClickListener{

    public SS1_Senha(Context context, AttributeSet attrs) {
        super(context, attrs);
        setPersistent(false);
        setDialogLayoutResource(R.layout.ss1_senha);

        setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //Action after OK

            }
        });


    }
}
Was it helpful?

Solution

You need to implement the DialogInterface.OnClickListener and handle the OnClick events of each buttons

Create a custom DialogPreference class like this

public class CustomDialogPreference extends DialogPreference implements DialogInterface.OnClickListener{

public CustomDialogPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    setPersistent(false);
    setDialogLayoutResource(R.layout.image_dialog);
    setPositiveButtonText("OK");
    setNegativeButtonText("CANCEL");
}

@Override
public void onClick(DialogInterface dialog, int which){
    if(which == DialogInterface.BUTTON_POSITIVE) {
        // do your stuff to handle positive button
    }else if(which == DialogInterface.BUTTON_NEGATIVE){
        // do your stuff to handle negative button
    }
 }
}

OTHER TIPS

if I understand correctly, you need to know about key pressed event in another classes (not in the SS1_Senha). For this you can use listeners (observers) pattern or handler.

To show an alert dialog you can use AlertDialog.builder. For example:

AlertDialog alertDialog = new AlertDialog.Builder(
                        AlertDialogActivity.this).create();

    // Setting Dialog Title
    alertDialog.setTitle("Alert Dialog");

    // Setting Dialog Message
    alertDialog.setMessage("My Message");


    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog closed
            Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
            }
    });

    // Showing Alert Message
    alertDialog.show();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top