LayoutInflater类有什么作用?(在Android中)

Aks*_*kar 31 android android-layout

我无法理解在Android中使用LayoutInflater.

LayoutInflater的作用究竟是什么,以及如何将它用于简单的Android应用程序?

S.D*_*.D. 54

什么是Layoutinflater?

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

LayoutInflater li = LayoutInflater.from(context);
Run Code Online (Sandbox Code Playgroud)

如何使用Layoutinflater?

你给它一个XML布局文件.您无需在R课堂上自动为您生成完整的文件地址,只需提供其资源ID .例如,一个布局文件,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

保存为/res/layout/my_layout.xml.

你给它LayoutInflater喜欢:

  View v = li.inflate(R.layout.my_layout,null,false);
Run Code Online (Sandbox Code Playgroud)

Layout Inflater做了什么?

v现在是一个LinearLayout对象(LinearLayout延伸View),并包含一个TextView对象,配置在确切顺序和设定,正如我们的所有属性描述在上面的XML.


TL; DR: A LayoutInflater读取XML,我们在其中描述了UI布局的方式.然后,它View从该XML为UI 创建实际对象.

  • @Mitulátbáti`findViewById`用于搜索**已创建的**视图. (8认同)
  • 除了View v = findViewById(R.layout.my_layout)之外,为什么它更好/更好; ?(抱歉这个蹩脚的问题我也是初学者) (2认同)

Sid*_*rth 13

当你跑步时setContentView(layout file name),你可以跑步findViewById(id of the widget).你不需要做类似的事情xyz.findViewById.您的应用程序的上下文设置为该布局文件,所有findBiewById调用都将引用该布局文件.

有些情况下,您需要再获取一个布局文件,如CustomDialog,ListElement或Custom Toast.此时您不想为这些小型UI组件创建一个Activity,那时您需要以编程方式获得对布局文件的编程引用,以便您可以在其上运行findViewById.

充气,像气球一样吹动布局,给你气球,让你可以看到它上面的所有颜色和物体:).Inflate为您提供对该布局的对象引用,以调用findViewById.

希望这清楚.


And*_*tic 5

LayoutInflater-的一些基础知识

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

  • 它永远不会直接使用.代替,

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