Dewey Reed
Dewey Reed

Reputation: 4956

How to get the inflated view from AlertDialog when using setView(int layoutResId)?

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).

Upvotes: 0

Views: 1988

Answers (4)

dominicoder
dominicoder

Reputation: 10155

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(...)

Upvotes: 3

parliament
parliament

Reputation: 371

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);

Upvotes: 0

Tanveer Munir
Tanveer Munir

Reputation: 1968

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.

Upvotes: 1

Chris623
Chris623

Reputation: 2532

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);

Upvotes: 1

Related Questions