【问题标题】:What does LayoutInflater class do? (in Android) [closed]LayoutInflater 类有什么作用? (在 Android 中)[关闭]
【发布时间】:2013-06-14 05:49:44
【问题描述】:

我无法理解 LayoutInflater 在 Android 中的使用。

LayoutInflater 的作用究竟是什么,如何将它用于一个简单的 Android 应用?

【问题讨论】:

  • developers.android 和公共互联网上的文档为此提供了很多信息......
  • LayoutInflater 允许您使用 XML 布局文件创建视图,该过程称为 inflate()
  • 检查this是否有帮助。

标签: android android-layout


【解决方案1】:

什么是 Layoutinflater ?

LayoutInflater 是一个类(一些实现或服务的包装器),你可以得到一个:

LayoutInflater li = LayoutInflater.from(context);

如何使用 Layoutinflater ?

你给它一个 XML 布局文件。您无需提供完整的文件地址,只需提供其资源 id,在 R 类中为您自动生成。例如,一个布局文件看起来像:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <TextView
            android:id="@+id/text_view"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

</LinearLayout>

保存为/res/layout/my_layout.xml

你把它给LayoutInflater就像:

  View v = li.inflate(R.layout.my_layout,null,false);

Layout Inflater 做了什么?

v 现在是一个 LinearLayout 对象 (LinearLayout extends View) ,并包含一个 TextView 对象,按确切顺序排列并设置了所有属性,如我们在上面的 XML 中描述了


TL;DR:LayoutInflater 读取一个 XML,我们在其中描述了我们想要的 UI 布局。然后它会根据该 XML 为 UI 创建实际的 Viewobjects。

【讨论】:

  • 为什么它比 View v = findViewById(R.layout.my_layout); ? (对不起,蹩脚的问题我也是初学者)
  • @Mitulátbáti findViewById 用于搜索已经创建的视图。
  • 其实就是在Java对象中转换自定义的XML布局。
【解决方案2】:

当您运行setContentView(layout file name) 时,您可以运行findViewById(id of the widget)。你不需要像xyz.findViewById 这样的事情。您应用的上下文设置为该布局文件,所有findBiewById 调用都将引用该布局文件。

在某些情况下,您需要再选择一个布局文件,例如 CustomDialog、ListElement 或 Custom Toast。这时候你不会想只为这些小的 UI 组件创建一个 Activity,那个时候你需要以编程方式获取对你的布局文件的编程引用,以便你可以在其上运行 findViewById。

充气,像气球一样吹出布局,给你一个气球,让你在它周围观察所有颜色和绘制在它上面的对象:)。 Inflate 为您提供对该布局的对象引用以调用 findViewById。

希望这一切都解决了。

【讨论】:

    【解决方案3】:

    LayoutInflater 的一些基础知识-

    • LayoutInflater 用于使用预定义的 XML 布局操作 Android 屏幕。
    • 该类用于将布局 XML 文件实例化为其对应的 View 对象。

    • 从不直接使用。相反,

    • 使用getLayoutInflater()getSystemService(String) 检索已经连接到当前上下文的标准LayoutInflater 实例。

    【讨论】:

      【解决方案4】:

      来自 Android 文档:

      将布局 XML 文件实例化到其对应的视图对象中。它从不直接使用。相反,使用 getLayoutInflater() 或 getSystemService(String) 来检索标准 LayoutInflater 实例,该实例已连接到当前上下文并为您正在运行的设备正确配置。例如:

      LayoutInflater inflater = (LayoutInflater)context.getSystemService
            (Context.LAYOUT_INFLATER_SERVICE);
      

      有助于创建自定义视图

      See

      【讨论】:

        【解决方案5】:

        它最有可能被关闭,但布局充气器的作用是从提供的布局文件中创建一个view

        View row=getLayoutInflater.inflate(R.layout.list_item,parent,false);
        

        它正在从R.layout.list_item 文件创建视图并证明view

        【讨论】:

          猜你喜欢
          • 2011-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-18
          • 2013-09-01
          • 2012-09-30
          • 1970-01-01
          • 2016-09-09
          相关资源
          最近更新 更多