【问题标题】:Avoid passing null as the view root (when inflating custom layout in AlertDialog)避免将 null 作为视图根传递(在 AlertDialog 中膨胀自定义布局时)
【发布时间】:2017-07-31 15:20:28
【问题描述】:

试图为 AlertDialog 增加自定义布局,但不断收到这种警告。我已经看到了几种不同的解决方案,但不知道哪种方案适合我的方案。消除此空警告的实际正确方法是什么?

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

【问题讨论】:

  • 没有,AFAIK,除了使用快速修复来抑制 Lint 警告。虽然总的来说 Lint 的建议是合理的,但这是我认为您无法访问父容器的情况之一。
  • 那么考虑到您的回复,使用@SuppressLint("InflateParams") View content = inflater.inflate(R.layout.dialog_customd, null); 是个好主意吗?
  • 这是否是一个“好主意”取决于您。 :-)
  • 酷。感谢您的提示。
  • 您知道如何使用this question 解决问题吗?我花了数周时间试图解决它,但没有运气。

标签: android android-layout android-alertdialog layout-inflater


【解决方案1】:

您可以尝试使用:

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

【讨论】:

    【解决方案2】:

    这样做:

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

    【讨论】:

      【解决方案3】:

      如果有人仍然像我一样面临这个问题,@Dmitry 的解决方案可以正常工作 -

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

      下面这行代码是不需要的 -

      LayoutInflater inflater = getActivity().getLayoutInflater();
      

      【讨论】:

        【解决方案4】:

        如果你使用视图绑定

        解决办法是:

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

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

        【讨论】:

          猜你喜欢
          • 2014-12-11
          • 2014-09-10
          • 2011-11-22
          • 2013-07-24
          • 1970-01-01
          • 2011-05-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多