Chris2222000
Chris2222000

Reputation: 67

Button onClick inside view used in Alert Dialog

I have a button inside a layout file that I am using to create a custom alert dialog. For unrelated reasons I need to use the buttons inside the layout as opposed to using the dialogs built-in buttons.

Its actually a very similar scenario to this question:

Android:Button in AlertDialog

The problem is that the onClick never seems to get called when I tap the button inside the alert dialog.

Here is the relevant portion of the code inside OnCreate in my activity:

LayoutInflater dcvI = LayoutInflater.from(this);
final View dcv = dcvI.inflate(R.layout.dialog,null);
final Button sd_abort = (Button)dcv.findViewById(R.id.abort1);
sd_abort.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {

//I do work here

}});

The alert dialog code:

View exp =  LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null,false);

new AlertDialog.Builder(MainActivity.this, R.style.CustomDialogTheme)
.setTitle("Warning!!!")
.setIcon(R.drawable.dhd_icon)
.setView(exp)
.show();

Does anyone know if I am missing something that is keeping the button and the onclick listener from connecting?

Thanks

Upvotes: 2

Views: 3457

Answers (1)

Neoh
Neoh

Reputation: 16164

You can create a new button listener class

public class ButtonListener implements OnClickListener {

    @Override
    public void onClick(View v) {
        // do your work

    }

}

then set them on both of your buttons

ButtonListener buttonListener = new ButtonListener();
sd_abort.setOnClickListener(buttonListener);

(in your dialog)

View exp =  LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null,false);

Button dialogButton = (Button)exp.findViewById(R.id.abort1);
dialogButton.setOnClickListener(buttonListener);
new AlertDialog.Builder(MainActivity.this, R.style.CustomDialogTheme)
.setTitle("Warning!!!")
.setIcon(R.drawable.dhd_icon)
.setView(exp)
.show();

Upvotes: 4

Related Questions