Avoid passing null as the view root (when inflating custom layout in AlertDialog)

Viewed 4648

Trying to inflate a custom layout for an AlertDialog, but keep getting this waring. I've seen several different solutions to this but don't know which is correct for my scenario. What is the actual correct way of getting rid of this null warning?

Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element)

@Override
public void onClick(View v) {
  AlertDialog alertDialog = new 
  AlertDialog.Builder(getActivity()).create();

  LayoutInflater inflater = getActivity().getLayoutInflater();
  View content = inflater.inflate(R.layout.dialog_customd, null);
  alertDialog.setView(content);

  alertDialog.show();
}
4 Answers

You may try to use:

View.inflate(context, R.layout.dialog_customd, null);

Incase someone still faces this issue like myself, @Dmitry's solution works fine -

View view = View.inflate(this, R.layout.dialog_set_height, null);

Below line of code is not required -

LayoutInflater inflater = getActivity().getLayoutInflater();

If you use viewbinding

the solution is:

LayoutInflater.from(context).inflate(R.layout.inflatedLayout, binding.root, false) as NativeAdView

So you can use binding.root as root

Related