Android 中的 LayoutInflater 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3477422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:22:19  来源:igfitidea点击:

What does LayoutInflater in Android do?

androidlayout-inflaterandroid-inflate

提问by user386430

What is the use of LayoutInflaterin Android?

LayoutInflater在安卓中有什么用?

采纳答案by Macarse

When you use a custom view in a ListViewyou must define the row layout. You create an xml where you place android widgets and then in the adapter's code you have to do something like this:

当您在 a 中使用自定义视图时,ListView您必须定义行布局。您创建一个 xml,在其中放置 android 小部件,然后在适配器的代码中,您必须执行以下操作:

public MyAdapter(Context context, List<MyObject> objects) extends ArrayAdapter {
  super(context, 1, objects);
  /* We get the inflator in the constructor */
  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  View view;
  /* We inflate the xml which gives us a view */
  view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);

  /* Get the item in the adapter */
  MyObject myObject = getItem(position);

  /* Get the widget with id name which is defined in the xml of the row */
  TextView name = (TextView) view.findViewById(R.id.name);

  /* Populate the row's xml with info from the item */
  name.setText(myObject.getName());

  /* Return the generated view */
  return view;
}

Read more in the official documentation.

官方文档中阅读更多内容

回答by Pentium10

The LayoutInflaterclass is used to instantiate the contents of layout XML files into their corresponding View objects.

LayoutInflater类用于布局XML文件的内容实例转换为其对应的视图对象。

In other words, it takes an XML file as input and builds the View objects from it.

换句话说,它将 XML 文件作为输入并从中构建 View 对象。

回答by Suragch

What does LayoutInflatordo?

有什么作用LayoutInflator

When I first started Android programming, I was really confused by LayoutInflaterand findViewById. Sometimes we used one and sometimes the other.

当我第一次开始 Android 编程时,我真的被LayoutInflater和弄糊涂了findViewById。有时我们使用一种,有时使用另一种。

  • LayoutInflateris used to create a new View(or Layout) object from one of your xml layouts.
  • findViewByIdjust gives you a reference to a view than has already been created. You might think that you haven't created any views yet, but whenever you call setContentViewin onCreate, the activity's layout along with its subviews gets inflated (created) behind the scenes.
  • LayoutInflater用于从您的 xml 布局之一创建新View(或Layout)对象。
  • findViewById只是给你一个比已经创建的视图的引用。你可能会认为你还没有创建任何意见还,但只要您拨打setContentViewonCreate,活动的,其子视图以及布局被充气(创建)幕后。

So if the view already exists, then use findViewById. If not, then create it with a LayoutInflater.

因此,如果视图已经存在,则使用findViewById. 如果没有,则使用LayoutInflater.

Example

例子

Here is a mini project I made that shows both LayoutInflaterand findViewByIdin action. With no special code, the layout looks like this.

下面是我做,同时显示一个小项目LayoutInflater,并findViewById在行动。没有特殊代码,布局看起来像这样。

enter image description here

在此处输入图片说明

The blue square is a custom layout inserted into the main layout with include(see herefor more). It was inflated automatically because it is part of the content view. As you can see, there is nothing special about the code.

蓝色方块是插入到主布局中的自定义布局include(有关更多信息,请参见此处)。它是自动膨胀的,因为它是内容视图的一部分。如您所见,代码没有什么特别之处。

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Now let's inflate (create) another copy of our custom layout and add it in.

现在让我们膨胀(创建)自定义布局的另一个副本并将其添加进去。

enter image description here

在此处输入图片说明

LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);

To inflate the new view layout, all I did was tell the inflater the name of my xml file (my_layout), the parent layout that I want to add it to (mainLayout), and that I don't actually want to add it yet (false). (I could also set the parent to null, but then the layout parameters of my custom layout's root view would be ignored.)

为了扩充新的视图布局,我所做的只是告诉 Inflater 我的 xml 文件的名称 ( my_layout),我想将它添加到 ( mainLayout)的父布局,并且我实际上还不想添加它 ( false) . (我也可以将父级设置为null,但是我的自定义布局的根视图的布局参数将被忽略。)

Here it is again in context.

这里又是在上下文中。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // inflate the main layout for the activity
        setContentView(R.layout.activity_main);

        // get a reference to the already created main layout
        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.activity_main_layout);

        // inflate (create) another copy of our custom layout
        LayoutInflater inflater = getLayoutInflater();
        View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);

        // make changes to our custom layout and its subviews
        myLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        TextView textView = (TextView) myLayout.findViewById(R.id.textView);
        textView.setText("New Layout");

        // add our custom layout to the main layout
        mainLayout.addView(myLayout);
    }
}

Notice how findViewByIdis used only after a layout has already been inflated.

注意 howfindViewById仅在布局已经膨胀后使用。

Supplemental Code

补充代码

Here is the xml for the example above.

这是上面示例的 xml。

activity_main.xml

活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main_layout"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <!-- Here is the inserted layout -->
    <include layout="@layout/my_layout"/>

</LinearLayout>

my_layout.xml

my_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@color/colorPrimary">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="5dp"
        android:textColor="@android:color/white"
        android:text="My Layout"/>

</RelativeLayout>

When do you need LayoutInflater

你什么时候需要 LayoutInflater

  • The most common time most people use it is in a RecyclerView. (See these RecyclerViewexamples for a listor a grid.) You have to inflate a new layout for every single visible item in the list or grid.
  • You also can use a layout inflater if you have a complex layout that you want to add programmatically (like we did in our example). You could do it all in code, but it is much easier to define it in xml first and then just inflate it.
  • 大多数人使用它的最常见时间是在RecyclerView. (请参阅列表网格的这些RecyclerView示例。)您必须为列表或网格中的每个可见项目扩充一个新布局。
  • 如果您想以编程方式添加复杂的布局(就像我们在我们的示例中所做的那样),您也可以使用布局充气器。您可以在代码中完成所有操作,但首先在 xml 中定义它然后只是对其进行膨胀要容易得多。

回答by Scott Hellam

LayoutInflater.inflate() provides a means to convert a res/layout/*.xml file defining a view into an actual View object usable in your application source code.

LayoutInflater.inflate() 提供了一种将定义视图的 res/layout/*.xml 文件转换为可在应用程序源代码中使用的实际 View 对象的方法。

basic two steps: get the inflater and then inflate the resource

基本两步:获取充气机,然后充气资源

How do you get the inflater?

你怎么得到充气机?

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

How do you get the view assuming the xml file is "list_item.xml"?

假设xml文件是“list_item.xml”,你如何获得视图?

View view = inflater.inflate(R.layout.list_item, parent, false);

回答by MSquare

Here is another example similar to the previous one, but extended to further demonstrate inflate parameters and dynamic behavior it can provide.

这是另一个与前一个类似的示例,但进行了扩展以进一步演示它可以提供的膨胀参数和动态行为。

Suppose your ListView row layout can have variable number of TextViews. So first you inflate the base item View (just like the previous example), and then loop dynamically adding TextViews at run-time. Using android:layout_weight additionally aligns everything perfectly.

假设您的 ListView 行布局可以具有可变数量的 TextView。所以首先你膨胀基础项目视图(就像前面的例子一样),然后在运行时动态地循环添加 TextViews。使用 android:layout_weight 还可以完美地对齐所有内容。

Here are the Layouts resources:

以下是布局资源:

list_layout.xml

list_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" >
    <TextView 
        android:id="@+id/field1"
        android:layout_width="0dp"  
        android:layout_height="wrap_content" 
        android:layout_weight="2"/>
    <TextView 
        android:id="@+id/field2"
        android:layout_width="0dp"  
        android:layout_height="wrap_content" 
        android:layout_weight="1"
/>
</LinearLayout>

schedule_layout.xml

schedule_layout.xml

<?xml version="1.0" encoding="utf-8"?>
   <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"  
    android:layout_height="wrap_content" 
    android:layout_weight="1"/>

Override getViewmethod in extension of BaseAdapter class

在 BaseAdapter 类的扩展中覆盖getView方法

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = activity.getLayoutInflater();
    View lst_item_view = inflater.inflate(R.layout.list_layout, null);
    TextView t1 = (TextView) lst_item_view.findViewById(R.id.field1);
    TextView t2 = (TextView) lst_item_view.findViewById(R.id.field2);
    t1.setText("some value");
    t2.setText("another value");

    // dinamically add TextViews for each item in ArrayList list_schedule
    for(int i = 0; i < list_schedule.size(); i++){
        View schedule_view = inflater.inflate(R.layout.schedule_layout, (ViewGroup) lst_item_view, false);
        ((TextView)schedule_view).setText(list_schedule.get(i));
        ((ViewGroup) lst_item_view).addView(schedule_view);
    }
    return lst_item_view;
}

Notedifferent inflate method calls:

注意不同的膨胀方法调用:

inflater.inflate(R.layout.list_layout, null); // no parent
inflater.inflate(R.layout.schedule_layout, (ViewGroup) lst_item_view, false); // with parent preserving LayoutParams

回答by Abhishek Singh Rathaur

This class is used to instantiate layout XML file into its corresponding Viewobjects. It is never be used directly -- use getLayoutInflater()or getSystemService(String)to retrieve a standard LayoutInflaterinstance that is already hooked up to the current context and correctly configured for the device you are running on. For example:

此类用于将布局 XML 文件实例化为其相应的View对象。它永远不会被直接使用——使用getLayoutInflater()getSystemService(String)检索LayoutInflater已经连接到当前上下文并为您正在运行的设备正确配置的标准实例。例如:

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

Reference: http://developer.android.com/reference/android/view/LayoutInflater.html

参考:http: //developer.android.com/reference/android/view/LayoutInflater.html

回答by Jijo

Inflating means reading the XML file that describes a layout (or GUI element) and to create the actual objects that correspond to it, and thus make the object visible within an Android app.

膨胀意味着读取描述布局(或 GUI 元素)的 XML 文件并创建与之对应的实际对象,从而使该对象在 Android 应用程序中可见。

final Dialog mDateTimeDialog = new Dialog(MainActivity.this);

// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);

// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);

This file could saved as date_time_dialog.xml:

这个文件可以保存为date_time_dialog.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DateTimeDialog" android:layout_width="100px"
    android:layout_height="wrap_content">
    <com.dt.datetimepicker.DateTimePicker
            android:id="@+id/DateTimePicker" android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    <LinearLayout android:id="@+id/ControlButtons"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_below="@+id/DateTimePicker"
            android:padding="5dip">
            <Button android:id="@+id/SetDateTime" android:layout_width="0dip"
                    android:text="@android:string/ok" android:layout_weight="1"
                    android:layout_height="wrap_content"
                   />
            <Button android:id="@+id/ResetDateTime" android:layout_width="0dip"
                    android:text="Reset" android:layout_weight="1"
                    android:layout_height="wrap_content"
                    />
            <Button android:id="@+id/CancelDialog" android:layout_width="0dip"
                    android:text="@android:string/cancel" android:layout_weight="1"
                    android:layout_height="wrap_content"
                     />
    </LinearLayout>

This file could saved as date_time_picker.xml:

这个文件可以保存为date_time_picker.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content" `enter code here`
    android:padding="5dip" android:id="@+id/DateTimePicker">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal">

    <LinearLayout
    android:id="@+id/month_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="1dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/month_plus"
        android:layout_width="45dp"
        android:layout_height="45dp"  
        android:background="@drawable/image_button_up_final"/>
    <EditText
        android:id="@+id/month_display"
        android:layout_width="45dp"
        android:layout_height="35dp"
        android:background="@drawable/picker_middle"
        android:focusable="false"
        android:gravity="center"
        android:singleLine="true"
        android:textColor="#000000">
    </EditText>
    <Button
        android:id="@+id/month_minus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
        android:background="@drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/date_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0.5dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/date_plus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
        android:background="@drawable/image_button_up_final"/>
    <EditText
        android:id="@+id/date_display"
        android:layout_width="45dp"
        android:layout_height="35dp"
        android:background="@drawable/picker_middle"
        android:gravity="center"
        android:focusable="false"
        android:inputType="number"
        android:textColor="#000000"
        android:singleLine="true"/>
    <Button
        android:id="@+id/date_minus"
        android:layout_width="45dp"
        android:layout_height="45dp"      
        android:background="@drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/year_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0.5dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/year_plus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
            android:background="@drawable/image_button_up_final"/>
    <EditText
        android:id="@+id/year_display"
        android:layout_width="45dp"
        android:layout_height="35dp"
        android:background="@drawable/picker_middle"
        android:gravity="center"
        android:focusable="false"
        android:inputType="number"
        android:textColor="#000000"
        android:singleLine="true"/>
    <Button
        android:id="@+id/year_minus"
        android:layout_width="45dp"
        android:layout_height="45dp"       
        android:background="@drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
        android:id="@+id/hour_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:id="@+id/hour_plus"
            android:layout_width="45dp"
            android:layout_height="45dp"          
            android:background="@drawable/image_button_up_final"/>
        <EditText
            android:id="@+id/hour_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:gravity="center"
            android:focusable="false"
            android:inputType="number"
            android:textColor="#000000"
            android:singleLine="true">
        </EditText>
        <Button
            android:id="@+id/hour_minus"
            android:layout_width="45dp"
            android:layout_height="45dp"       
            android:background="@drawable/image_button_down_final"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/min_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0.35dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:id="@+id/min_plus"
            android:layout_width="45dp"
            android:layout_height="45dp"       
            android:background="@drawable/image_button_up_final"/>
        <EditText
            android:id="@+id/min_display"
            android:layout_width="45dp"
            android:layout_height="35dp"
            android:background="@drawable/picker_middle"
            android:gravity="center"
            android:focusable="false"
            android:inputType="number"
            android:textColor="#000000"
            android:singleLine="true"/>
        <Button
            android:id="@+id/min_minus"
            android:layout_width="45dp"
            android:layout_height="45dp"       
            android:background="@drawable/image_button_down_final"/>
    </LinearLayout>

    <LinearLayout 
        android:id="@+id/meridiem_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0.35dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"
        android:gravity="center"
        android:orientation="vertical">
        <ToggleButton 
            android:id="@+id/toggle_display"
            style="@style/SpecialToggleButton"
            android:layout_width="40dp"
            android:layout_height="32dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="45dp"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="5dp"
            android:padding="5dp"
            android:gravity="center"
            android:textOn="@string/meridiem_AM"
            android:textOff="@string/meridiem_PM"
            android:checked="true"/>

           <!--  android:checked="true" --> 

    </LinearLayout>
</LinearLayout>
</RelativeLayout>

The MainActivityclass saved as MainActivity.java:

MainActivity保存为MainActivity.java的类:

public class MainActivity extends Activity {
    EditText editText;
    Button button_click;
    public static Activity me = null;
    String meridiem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText)findViewById(R.id.edittext1);
        button_click = (Button)findViewById(R.id.button1);
        button_click.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view){
                final Dialog mDateTimeDialog = new Dialog(MainActivity.this);
                final RelativeLayout mDateTimeDialogView = (RelativeLayout)   getLayoutInflater().inflate(R.layout.date_time_dialog, null);
                final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
                // mDateTimePicker.setDateChangedListener();
                ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        mDateTimePicker.clearFocus();
                        int hour = mDateTimePicker.getHour();
                        String result_string = mDateTimePicker.getMonth() +" "+   String.valueOf(mDateTimePicker.getDay()) + ", " + String.valueOf(mDateTimePicker.getYear())
                        + "  " +(mDateTimePicker.getHour()<=9? String.valueOf("0"+mDateTimePicker.getHour()) : String.valueOf(mDateTimePicker.getHour())) + ":" + (mDateTimePicker.getMinute()<=9?String.valueOf("0"+mDateTimePicker.getMinute()):String.valueOf(mDateTimePicker.getMinute()))+" "+mDateTimePicker.getMeridiem();
                        editText.setText(result_string);
                        mDateTimeDialog.dismiss();
                    }
                });
                // Cancel the dialog when the "Cancel" button is clicked
                ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mDateTimeDialog.cancel();
                    }
                });
                // Reset Date and Time pickers when the "Reset" button is clicked
                ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        mDateTimePicker.reset();
                    }
                });

                // Setup TimePicker
                // No title on the dialog window
                mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                // Set the dialog content view
                mDateTimeDialog.setContentView(mDateTimeDialogView);
                // Display the dialog
                mDateTimeDialog.show();
            }
        });
    }
}

回答by Zahan Safallwa

What inflater does

充气机有什么作用

It takes a xml layout as input (say) and converts it to View object.

它需要一个 xml 布局作为输入(比如说)并将其转换为 View 对象。

Why needed

为什么需要

Let us think a scenario where we need to create a custom listview. Now each row should be custom. But how can we do it. Its not possible to assign a xml layout to a row of listview. So, we create a View object. Thus we can access the elements in it (textview,imageview etc) and also assign the object as row of listview

让我们考虑一个需要创建自定义列表视图的场景。现在每一行都应该是自定义的。但是我们怎么做。无法将 xml 布局分配给一行列表视图。所以,我们创建了一个 View 对象。因此我们可以访问其中的元素(textview、imageview 等)并将对象分配为 listview 的行

So, whenever we need to assign view type object somewhere and we have our custom xml design we just convert it to object by inflater and use it.

因此,每当我们需要在某处分配视图类型对象并且我们有自定义 xml 设计时,我们只需通过 inflater 将其转换为对象并使用它。

回答by Arry

LayoutInflateris a class used to instantiate layout XML file into its corresponding view objects which can be used in Java programs. In simple terms, there are two ways to create UI in android. One is a static way and another is dynamic or programmatically. Suppose we have a simple layout main.xml having one textviewand one edittextas follows.

LayoutInflater是一个类,用于将布局 XML 文件实例化为其相应的视图对象,可在 Java 程序中使用。简单来说,在android中有两种创建UI的方法。一种是静态方式,另一种是动态或编程方式。假设我们有一个有一个简单的布局main.xml中textview,一个edittext如下。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/layout1"
    >
<TextView
        android:id="@+id/namelabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter your name"
        android:textAppearance="?android:attr/textAppearanceLarge" >
    </TextView>
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="14dp"
        android:ems="10">
    </EditText>
</LinearLayout>

We can display this layout in static way by

我们可以通过以下方式以静态方式显示此布局

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

A dynamic way of creating a view means the view is not mentioned in our main.xml but we want to show with this in run time. For example, we have another XML in layout folder as footer.xml

创建视图的动态方式意味着我们的 main.xml 中未提及该视图,但我们希望在运行时显示此视图。例如,我们在布局文件夹中有另一个 XML 作为 footer.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TextView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="Add your record"
    android:textSize="24sp" >
 </TextView>

We want to show this textbox in run time within our main UI. So here we will inflate text.xml. See how:

我们希望在运行时在主 UI 中显示此文本框。所以在这里我们将膨胀 text.xml。怎么看:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  TextView t = (TextView)inflater.inflate(R.layout.footer,null);

  lLayout = (LinearLayout)findViewById(R.id.layout1);
  lLayout.addView(t);

Here I have used getSystemService (String) to retrieve a LayoutInflater instance. I can use getLayoutInflator() too to inflate instead of using getSystemService (String) like below:

在这里,我使用了 getSystemService (String) 来检索 LayoutInflater 实例。我也可以使用 getLayoutInflator() 来膨胀,而不是使用 getSystemService (String) 如下所示:

LayoutInflator inflater = getLayoutInflater();
TextView t = (TextView) inflater.inflate(R.layout.footer, null);
lLayout.addView(t);

回答by Gal Rom

here is an example for geting a refrence for the root View of a layout , inflating it and using it with setContentView(View view)

这是一个示例,用于获取布局的根视图的引用,对其进行膨胀并将其与 setContentView(View view) 一起使用

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater li=getLayoutInflater();
    View rootView=li.inflate(R.layout.activity_main,null);
    setContentView(rootView);


}