Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure custom button in dialog?

Tags:

android

dialog

here I have a custom dialog with background 2 ImageButton inside it. the problem is, when I try to set onclick listener to that buttons, the program will return NullPointerException. I don't know why is this happen. how to assign operation to button inside dialog anyway??

pause menu xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:background="@drawable/pause_menu_cropped" android:layout_gravity="center" android:gravity="center|center_horizontal">
    <TableLayout android:layout_width="wrap_content" android:id="@+id/tableLayout1" android:layout_height="wrap_content">
        <ImageButton android:src="@drawable/pause_button_option" android:layout_width="wrap_content" android:background="@drawable/pause_button_option" android:layout_height="wrap_content" android:id="@+id/btn_pause_option"></ImageButton>
        <ImageButton android:src="@drawable/pause_button_quit" android:layout_width="wrap_content" android:background="@drawable/pause_button_quit" android:layout_height="wrap_content" android:id="@+id/btn_pause_quit"></ImageButton>
    </TableLayout>
</LinearLayout>

dialog code

        Dialog pauseMenu = new Dialog(this, R.style.NewDialog);
    pauseMenu.setContentView(R.layout.pause_menu);

  ImageButton quit = (ImageButton)findViewById(R.id.btn_pause_quit);
  quit.setOnClickListener(
          new OnClickListener() {

      @Override
      public void onClick(View v) {
          TestActivity.this.finish();
      }
  });
    return pauseMenu;

the code is returning error in line

quit.setOnClickListener();
like image 434
Fugogugo Avatar asked Dec 06 '25 04:12

Fugogugo


1 Answers

ImageButton quit = (ImageButton)findViewById(R.id.btn_pause_quit);

should be

ImageButton quit = (ImageButton)pauseMenu.findViewById(R.id.btn_pause_quit);

This happens because findViewById is invoked for the activity, and it doesn't have btn_pause_quit button in it's layout. But your dialog has.

like image 120
Vladimir Ivanov Avatar answered Dec 08 '25 16:12

Vladimir Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!