0

I use this code to create a custom AlertDialog:

val dialog = AlertDialog.Builder(context)
            .setView(R.layout.layout)
            .create()

The problem is I cannot get the inflated view. dialog.findViewById(R.id.a_view_in_the_layout) returns null.

Alternatively, I can use .setView(View.inflate(context, R.layout.layout, null) but this sometimes makes the dialog fill the screen and take more space than setView(int layoutResId).

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41

4 Answers4

3

If I remember correctly, create sets up the Dialog, but its layout is not inflated until it needs to be shown. Try calling show first then, then finding the view you're looking for.

val dialog = AlertDialog.Builder(context)
            .setView(R.layout.layout)
            .create()

dialog.show() // Cause internal layout to inflate views
dialog.findViewById(...)
dominicoder
  • 9,338
  • 1
  • 26
  • 32
1

Just inflate the layout yourself (its Java code but I think you know what to do):

AlertDialog.Builder dialog = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate( R.layout.layout, null );
dialog.setView(view);
dialog.create().show();

Your inflated view is now view and you can use it to find other views in it like:

EditText editText = view.findViewById(R.id.myEdittext);
Chris623
  • 2,464
  • 1
  • 22
  • 30
1

Instead of using alert dialog use simple Dialog its Easy and very simple

final Dialog dialog = new Dialog(context);
        dialog.setContentView((R.layout.layout);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle);
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

You don't have to need to inflate the View.

Tanveer Munir
  • 1,956
  • 1
  • 12
  • 27
0

Try this;

View dialogView; //define this as a gobal field

dialogView = LayoutInflater.from(context).inflate(R.layout.your_view, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setView(dialogView);

View yourView = dialogView.findViewById(R.id.a_view_in_the_layout);
TextView yourTextView = dialogView.findViewById(R.id.a_textView_in_the_layout);
Button yourButton = dialogView.findViewById(R.id.a_button_in_the_layout);
parliament
  • 371
  • 1
  • 5
  • 18