避免将null作为视图根(当在AlertDialog中填充自定义布局时)。

5
尝试为AlertDialog充气自定义布局,但是一直收到此警告。我见过几种不同的解决方案,但不知道哪个是适合我的情况的正确解决方法。实际上,有什么正确的方法可以消除这个null警告吗?

避免将null作为视图根传递(需要在充气布局的根元素上解析布局参数)

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

1
据我所知,除了使用快速修复来抑制 Lint 警告之外,没有其他方法。虽然通常 Lint 的建议是正确的,但这是其中一种情况,我认为您无法访问父容器。 - CommonsWare
那么考虑到你的回答,使用@SuppressLint("InflateParams") View content = inflater.inflate(R.layout.dialog_customd, null);是一个好主意吗? - wbk727
1
这是否是一个“好主意”,取决于你。 :-) - CommonsWare
很棒。谢谢你的提示。 - wbk727
你有任何想法如何解决这个问题吗?我已经花了几周的时间尝试解决它,但是没有成功。 - wbk727
使用View content = inflater.inflate(R.layout.dialog_customd, parent, false); - Attaullah
4个回答

10

您可以尝试使用:

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

4

按照下列方法操作:

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

1
如果有人像我一样仍然遇到这个问题,@Dmitry的解决方案很好用 -
View view = View.inflate(this, R.layout.dialog_set_height, null);

以下代码行不是必需的 -
LayoutInflater inflater = getActivity().getLayoutInflater();

0

如果您使用ViewBinding

解决方案如下:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接