Reputation: 5786
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?
Upvotes: 1
Views: 1425
Reputation: 449
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();
Upvotes: 1
Reputation: 5134
in your case use
Button mButton = (Button)(inflater.inflate(R.layout.dialog, null)). findViewById(R.id.button1);
Upvotes: 1
Reputation: 14398
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);
Upvotes: 1
Reputation: 3723
U can customize full alert dialog as per requirement.. check this answer.. Android - change dialog button location
Upvotes: 1
Reputation: 157437
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
Upvotes: 1
Reputation: 1857
You can access a Button Like this way
Button dialogButton = (Button) alert11.findViewById(R.id.button1);
Upvotes: 1