我是 Android 的新手..所以我不知道我是否在问一个愚蠢的问题。 不管怎样,它就在这里..
我们知道..我们像这样在java中实例化一个对象:
Sagar sagarObject = new Sagar();
Sagar 所在的类
但我刚刚在android中看到了一段代码:
LayoutInfalter sagarsInflater = LayoutInflater.from(getContext());
其中 layoutInflater 是类。
现在我无法理解上面的代码。不应该是这样的:
LayoutInflater sagarsInflater = new LayoutInflater();
为什么我们没有实例化那个对象?为什么在没有实例化的情况下自动使用这种“from”方法?
另一个例子,
View customView = sagarsInflater.inflate(R.layout.custom_row, parent, false);
这里我们也没有像这样从 View 类实例化对象:
View customView = new View();
相反,我们使用了我们之前制作的 sagarsInflater 方法。
最佳答案
首先,即使你认为你问的是非常基础的东西,但如果是你不知道的东西,那永远不会是一个愚蠢的问题。
您应该查看文档以更好地理解 LayoutInflater:
https://developer.android.com/reference/android/view/LayoutInflater.html
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use getLayoutInflater() or getSystemService(Class) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.
因此您必须从上下文中获取现有实例 LayoutInflater
,而不是创建新实例。这就是为什么你不能使用类似的东西
LayoutInflater inflater = new LayoutInflater();
从文档中您发现访问 LayoutInflater
的正确方法是:
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
但是您正在使用 LayoutInflater.from(Context context)
。如果我们查看它的实现,我们会发现以下代码:
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
我们可以看到它正在从作为参数传递的上下文中检索 layoutInflater。
关于调用该方法的方式,它像Class.method
一样使用,因为它被定义为static。这意味着方法属于类,而不属于对象的实例。
有关此的更多信息: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
为了理解与 View 相关的问题:
你可以像这样实例化一个对象View
View view = new View(context);
View 实例将是一个具有默认属性的 View 对象,它不会附加到任何父 View 。例如,您可以使用它从代码创建动态布局。
为什么要使用 inflater.inflate(int resource, ViewGroup root, boolean attachToRoot);
?
因为您想从 xml 布局中扩充 View 。这就是我们使用 LayoutInflater
的目的。
再次检查文档以获得更好的解释:
希望对您有所帮助。
关于java - 为什么我们不需要在Android中实例化LayoutInflater?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785729/