有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java找不到“避免将null作为视图根传递”的父级

我有这样的代码,在这里我定义了我自己的AlertDialog.Builder

public class UnlockDialog extends AlertDialog.Builder {
    public UnlockDialog(Activity context) {
        super(context);

        LayoutInflater inflater = context.getLayoutInflater();
        View dlgView = inflater.inflate(R.layout.unlock_dialog, null); 
        setView(dlgView);
    }
}

代码工作正常,但我在inflater.inflate调用中收到一条警告:

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

我的适配器中也有这个问题,我可以通过提供parentfalse来解决它,正如我在这里发现的:Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element)

然而,在上面的例子中,我似乎没有可用的parent。我试过了,但没用


共 (1) 个答案

  1. # 1 楼答案

    警告不应适用于这种情况。当attachToRoot为false时,root参数仅用于调用其generateDefaultLayoutParams()方法并将结果LayoutParams分配给膨胀视图

    在这种情况下,对话框将覆盖它们,因此它们无论如何都不会被使用

    请检查this article,特别是部分,每个规则都有一个例外

    However, because the result will go into the dialog, which does not expose its root view (in fact, it doesn’t exist yet), we do not have access to the eventual parent of the layout, so we cannot use it for inflation. It turns out, this is irrelevant, because AlertDialog will erase any LayoutParams on the layout anyway and replace them with match_parent.