避免将 null 作为视图根传递(在 AlertDialog 中扩展自定义布局时)

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

正在尝试为 AlertDialog 扩展自定义布局,但不断收到此警告。我已经看到了几种不同的解决方案,但不知道哪个适合我的场景。摆脱此空警告的实际正确方法是什么?

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

这样做:

View content = inflater.inflate(R.layout.dialog_customd, parent, false);

您可以尝试使用:

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

万一有人像我一样面临这个问题,@Dmitry 的解决方案工作正常 -

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

下面一行代码不需要-

LayoutInflater inflater = getActivity().getLayoutInflater();

如果您使用视图绑定

解决方法是:

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

所以你可以使用binding.root作为root