1

I have created a custom alert dialog using the following code -

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = this.getLayoutInflater();

builder.setView(inflater.inflate(R.layout.dialog, null))
       .setTitle("test")
       .setCancelable(true);

AlertDialog alert11 = builder.create();
alert11.show();

Here is the code of the layout dialog.xml which is used in the alert dialog -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set"/>

</LinearLayout>

Now, how to get a reference of the button to set a click listener?

I tried this -

Button mButton = (Button) findViewById(R.id.button1);

but I get an exception -

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference

Is there any other way to access the button?

Confuse
  • 5,646
  • 7
  • 36
  • 58

6 Answers6

1

You can access a Button Like this way

Button dialogButton = (Button) alert11.findViewById(R.id.button1);
Rajan Bhavsar
  • 1,977
  • 11
  • 25
1

you are looking for the button in the wrong place.

View view = inflater.inflate(R.layout.dialog, null);
builder.setView(view)
       .setTitle("test")
       .setCancelable(true);

and then use view to look for your buotton

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

U can customize full alert dialog as per requirement.. check this answer.. Android - change dialog button location

Community
  • 1
  • 1
Ankit Kumar
  • 3,663
  • 2
  • 26
  • 38
1

First inflate your custom view as

View dialoglayout = inflater.inflate(R.layout.dialog, null);

then use dialoglayout as

  builder.setView(dialoglayout)
   .setTitle("test")
   .setCancelable(true);

and now find button as

Button mButton = (Button) dialoglayout.findViewById(R.id.button1);
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
1

in your case use

Button mButton = (Button)(inflater.inflate(R.layout.dialog, null)). findViewById(R.id.button1);
Kunu
  • 5,078
  • 6
  • 33
  • 61
1

Use this code which will solve your problem-

View view = (LinearLayout) getLayoutInflater()
                .inflate(R.layout.dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(view);
final AlertDialog mDialog = builder.create();
mDialog.setCancelable(false);

Button mButton = (Button) view.findViewById(R.id.button1);
mDialog.show();
Mohit Rajput
  • 439
  • 3
  • 18