-1

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();
Pankaj
  • 7,908
  • 6
  • 42
  • 65
BlazE
  • 81
  • 1
  • 16
  • 1
    I didn't get what you meant by "created in a new file, thus, it crashes the app". What happens when you try to find the buttons by their ids `d.findViewById(R.id.continue_button);`? – AndroidEx Jun 07 '15 at 20:23
  • Nothing happens when I do it like that. But what's the use of that anyway? I mean, if that's how I find the ID of the button, how do I set up the onClickListener then? – BlazE Jun 07 '15 at 20:30
  • 1
    You already have the ids of your buttons. `Dialog.findViewById()` returns you a corresponding `View` for which you can set a listener: `view.setOnClickListener(...);`. – AndroidEx Jun 07 '15 at 20:33
  • Initialise your button as Android777 suggested. – Pankaj Jun 07 '15 at 20:34
  • Perfect! It worked, now I understand how this works. Thanks :) – BlazE Jun 07 '15 at 20:35

1 Answers1

0

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 ;)

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148