我收到 lint 警告,
Avoid passing null as the view root
当使用 null
作为 parent
膨胀视图时,例如:
LayoutInflater.from(context).inflate(R.layout.dialog_edit, null);
但是view要作为一个
AlertDialog
的内容,在setView
上使用AlertDialog.Builder
,所以我不知道应该传递什么作为parent
.
你认为
parent
在这种情况下应该是什么?
使用此代码在没有警告的情况下膨胀对话框视图:
View.inflate(context, R.layout.dialog_edit, null);
简短的故事是,当您为对话框膨胀视图时,
parent
应该为空,因为在视图膨胀时它是未知的。在这种情况下,您可以通过三种基本解决方案来避免警告:
inflate(int resource, ViewGroup root, boolean attachToRoot)
。将 attachToRoot
设置为 false
。这会告诉充气器父级不可用。查看 http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ 对这个问题的精彩讨论,特别是末尾的“每个规则都有例外”部分。
你应该使用
AlertDialog.Builder.setView(your_layout_id)
,所以你不需要给它充气。
创建对话框后使用
AlertDialog.findViewById(your_view_id)
。
使用
(AlertDialog) dialogInterface
在dialog
内获得OnClickListener
然后dialog.findViewById(your_view_id)
.
在 ViewGroup 解决警告时强制转换为空:
View dialogView = li.inflate(R.layout.input_layout,(ViewGroup)null);
其中
li
是LayoutInflater's
对象。
您不需要为对话指定
parent
。
使用覆盖顶部的
@SuppressLint("InflateParams")
来抑制它。
编辑:
在写这个答案的时候,我并不知道 Lint 抑制。最好抑制 Lint 而不是欺骗 IDE。将其添加到行或方法上方:
@SuppressLint("InflateParams")
旧答案:
当你真的没有任何
parent
(例如为AlertDialog
创建视图)时,你别无选择,只能通过null
。所以这样做是为了避免警告:
// Java
final ViewGroup nullParent = null;
convertView = infalInflater.inflate(R.layout.list_item, nullParent);
// Kotlin
val nullParent: ViewGroup? = null
val convertView = layoutInflater.inflate(R.layout.my_dialog, nullParent)
根据https://developer.android.com/guide/topics/ui/dialogs
膨胀并设置对话框的布局
将 null 作为父视图传递,因为它会进入对话框布局
因此,为了创建 AlertDialog,我使用
@SuppressLint("InflateParams")
LayoutInflater inflater = requireActivity().getLayoutInflater();
@SuppressLint("InflateParams")
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view);
据我所知,AlertDialog 是唯一可以安全地使用 null 而不是父视图的情况。在这种情况下,您可以使用以下方式抑制警告:
@SuppressLint(“InflateParams”)
一般来说,您永远不应该使用 SupressLint 或其他答案中提到的解决方法之一来消除警告。父视图对于评估在正在膨胀的视图的根元素中声明的布局参数是必需的。这意味着如果您使用 null 而不是父视图,则根元素中的所有 Layout Params 将被忽略并替换为默认 Layout Params。大多数时候它会很好,但在某些情况下它会导致一个非常难以发现的错误。
Android 的文档 (AlertDialog) 说:
如果您想显示更复杂的视图,请查找名为“自定义”的 FrameLayout 并将您的视图添加到其中:
FrameLayout fl = findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
因此,我们可以在我们的案例中使用
fl
作为父母:
FrameLayout fl = findViewById(android.R.id.custom);
View view = LayoutInflater.from(context).inflate(R.layout.custom_dialog, fl, false);
有效,但我不确定它是否有效
从
View.inflate()
的文档,它说
从 XML 资源扩展视图。这个方便的方法包装了
LayoutInflater
类,它提供了全方位的视图膨胀选项。
@param context The Context object for your activity or application.
@param resource The resource ID to inflate
@param root A view group that will be the parent. Used to properly inflate the layout_* parameters.
而不是做
view = inflater.inflate(R.layout.list_item, null);
做
view = inflater.inflate(R.layout.list_item, parent, false);
它会使用给定的父级对其进行膨胀,但不会将其附加到父级。
非常感谢 Coeffect(链接到他的帖子)