Android - How to check for button click in a custom alert dialog box?

1.5k views Asked by At

I've got two buttons: Share, Continue. Both of them are created in a new XML file because I wanted to keep my application with a nice flat Windows 8/10 looking GUI.

I am able to display the dialog message, but the problem I am facing is, how can I check which button was clicked by the user: Share or Continue? I can't set up the onClickListener for them because this alert dialog has been created in a new file, thus, it crashes the app if I try to do so.

Here's the XML code for the buttons:

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@+id/share_button"
    android:layout_marginRight="5dp"
    android:text="SHARE"
    android:textColor="#FFFFFF"
    android:textSize="16sp"
    android:background="@drawable/button_blue" />

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@+id/continue_button"
    android:layout_marginLeft="5dp"
    android:text="CONTINUE"
    android:textColor="#FFFFFF"
    android:textSize="16sp"
    android:background="@drawable/button_green" />

And the java code where I display this as an alert dialog:

Dialog d = new Dialog(MainActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.dialog);
d.show();
1

There are 1 answers

0
Skizo-ozᴉʞS ツ On BEST ANSWER

You can call it by your dialog d i.e :

    Dialog d = new Dialog(MainActivity.this);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.setContentView(R.layout.dialog);
    Button button = (Button) d.findViewById(R.id.share_button);
    Button button2 = (Button) d.findViewById(R.id.continue_button)
    d.show();

And then you can make a normal onClickListener

button.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
      //STUFF
  }
});

Hope it helps ;)