Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a View of an AlertDialog

Tags:

android

I want to get a View from an AlertDialog:

Button R = (Button) findViewById(R.id.toggleButtonA);

But if I do this, it always is null. What can I do to get and edit the view?

Here are the relevant parts of code:

What creates the Dialog:

public void openSelection(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.dialayout, null));
    AlertDialog dialog = builder.create();
    dialog.show();
}

The dialayout.xml

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

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/toggleButtonA"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:onClick="select"
        android:text="All"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toggleButtonM" />


</android.support.constraint.ConstraintLayout>

</LinearLayout>
like image 900
newToEverything Avatar asked Apr 09 '17 23:04

newToEverything


2 Answers

You need to assign your inflated view to a variable first. Example:

public void openSelection(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    LayoutInflater inflater = this.getLayoutInflater();
    View v = inflater.inflate(R.layout.activity_main, null);  // this line
    builder.setView(v);
    AlertDialog dialog = builder.create();
    dialog.show();

    Button RR = (Button) v.findViewById(R.id.toggleButtonA); // this is how you get a view of the button
}

Please reneame your button variable name R to another name perhaps because R is a reserved word.

like image 108
Zarul Izham Avatar answered Oct 17 '22 23:10

Zarul Izham


Inflate the parent layout first,

 LayoutInflater inflater = this.getLayoutInflater();
View parent = inflater.inflate(R.layout.activity_main, null);

then set your builder to that parent view.builder.setView(parent);

you can then perform any view finding with that parent inflated view. Or you can call AlertDialog diag = builder.create(); and perform a find with the diag.findViewById(R.id.name);

so Button btR = (Button) diag.findViewById(R.id.toggleButtonA);

or Button btR = (Button)parent.findViewById(R.id.toggleButtonA);

like image 23
Remario Avatar answered Oct 18 '22 00:10

Remario