问题描述
我无法理解Android中LayoutInflater的使用.
I am unable to understand the use of LayoutInflater in Android.
LayoutInflater的确切作用是什么,以及如何将其用于简单的Android应用程序?
What exactly is the role of LayoutInflater, and how to use it for a simple Android app?
推荐答案
什么是Layoutinflater?
LayoutInflater
是一个类(某些实现或服务的包装),您可以获取一个:
LayoutInflater
is a class (wrapper of some implementation or service), you can get one:
LayoutInflater li = LayoutInflater.from(context);
如何使用Layoutinflater?
您向其提供XML布局文件.您无需提供完整的文件地址,只需提供R
类中为您自动生成的文件资源ID.例如,布局文件如下所示:
You feed it an XML layout file. You need not give full file address, just its resource id, generated for you automatically in R
class. For example, a layout file which look like:
<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
:
You give it to LayoutInflater
like:
View v = li.inflate(R.layout.my_layout,null,false);
Layout Inflater是做什么的?
该v
现在是一个LinearLayout
对象,并且包含一个TextView
对象,该对象按准确的顺序排列并设置了所有属性,我们在上面的XML中描述了.
That v
is now a LinearLayout
object , and contains a TextView
object, arranged in exact order and with all properties set, as we described in the XML above.
TL; DR::LayoutInflater
读取XML,其中描述了我们希望UI布局如何.然后,它将根据该XML为UI创建实际的View
对象.
TL;DR: A LayoutInflater
reads an XML in which we describe how we want a UI layout to be. It then creates actual View
objects for UI from that XML.
这篇关于LayoutInflater类做什么? (在Android中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!