膨胀vs findViewById

16 android

假设我有一个简单的布局xml,如下所示:

button.xml:

<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
Run Code Online (Sandbox Code Playgroud)

以下电话有什么不同吗?我应该使用哪一个?

button = (Button) getLayoutInflater().inflate(R.layout.button, null);
Run Code Online (Sandbox Code Playgroud)

View v = getLayoutInflater().inflate(R.layout.button, null);
button = (Button) v.findViewById(R.id.button01);
Run Code Online (Sandbox Code Playgroud)

Rob*_*bin 15

这个创建一个具有给定布局的新视图,其中'R.layout.button'是由xml文件'button.xml'的名称生成的.每次调用.inflate(...),您都会获得一个新实例.

View v = getLayoutInflater().inflate(R.layout.button, null);
Run Code Online (Sandbox Code Playgroud)

-

当那个人在布局中找到一个现有的视图,其中R.id.button01是由id名称'android:id ="@ + id/button01"'生成的.每次调用.findViewById(R.id.button01)时,您将获得相同的实例,因为视图'v'将是相同的.

button = (Button) v.findViewById(R.id.button01);
Run Code Online (Sandbox Code Playgroud)


Rom*_*rik 0

第一个选项更干净并且效率更高。

您的布局充气机将返回一个Button. 使用第一个选项,您可以直接访问Button。使用第二个选项,您将按钮向下转换为 a View,然后查找具有给定 ID 的视图,这是额外无用的比较,因为具有您在层次结构中查找的 ID 的视图恰好是按钮本身。所以在第二个选项中,v == button.