【问题标题】:What does LayoutInflater in Android do?Android 中的 LayoutInflater 有什么作用?
【发布时间】:2011-03-29 11:47:40
【问题描述】:

LayoutInflater在Android中有什么用?

【问题讨论】:

  • 检查this是否有帮助。

标签: android layout-inflater android-inflate


【解决方案1】:

LayoutInflater 类用于将布局 XML 文件的内容实例化为它们对应的 View 对象。

换句话说,它接受一个 XML 文件作为输入并从中构建视图对象。

【讨论】:

  • 我正在寻找的是“换句话说”部分,因为顶部已经在 API 文档中
  • 这对我来说仍然很抽象。所以,假设我有一个single_list_item.xml 文件,用于ListView 的每一行。使用那个 XML 文件是不是有点像充气机?
  • 事实上,API 文档说明了一切。实例化 XML 的内容是准确的描述。有时我们读得太深而忽略了明显的内容
【解决方案2】:

LayoutInflator 是做什么的?

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

  • LayoutInflater 用于从您的一种 xml 布局创建一个新的 View(或 Layout)对象。
  • findViewById 只是为您提供了对已创建视图的引用。您可能认为您还没有创建任何视图,但每当您在 onCreate 中调用 setContentView 时,活动的布局及其子视图都会在幕后膨胀(创建)。

所以如果视图已经存在,那么使用findViewById。如果没有,则使用LayoutInflater 创建它。

示例

这是我制作的一个迷你项目,展示了LayoutInflaterfindViewById 的实际应用。没有特殊代码,布局是这样的。

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

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

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

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

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

这里又是上下文。

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);
    }
}

请注意 findViewById 仅在布局已膨胀后使用。

补充代码

这是上面示例的 xml。

activity_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

<?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>

什么时候需要 LayoutInflater

  • 大多数人最常使用它的时间是RecyclerView。 (有关listgrid,请参阅这些RecyclerView 示例。)您必须为列表或网格中的每个可见项目扩展一个新布局。
  • 如果您想要以编程方式添加复杂的布局(就像我们在示例中所做的那样),您也可以使用布局充气器。您可以在代码中完成这一切,但先在 xml 中定义它然后再膨胀它会更容易。

【讨论】:

  • 比标记为解决方案的答案要好得多的解释。有时生活并不公平。
  • 您好,先生,如果我在 main_activity.xml 中有多个视图,那么我如何在 main_activity 中设置 external.xml 视图并使用中心 layout_gravity。
  • 这应该是公认的答案。对于任何初学者来说都很容易理解。
  • mylayout 是 View 类型还是 LinearLayout 类型?
  • @HSSingh, myLayout 是一个视图,尽管我可以将它膨胀为一个相对布局(参见 my_layout.xml)。膨胀后,我将其添加为 LinearLayout 父级的子视图(即mainLayout)。
【解决方案3】:

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

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;
}

official documentation 中了解更多信息。

【讨论】:

  • 理想情况下你应该先测试 convertView 看看你是否可以回收资源,所以View view = convertView; if (view == null) { view = mInflater.... }
  • 我认为这个答案并不能真正解释 LayoutInflater 是什么,尽管它解释了在哪里使用它。答案是 1-down 更好。
  • 这并没有解释什么是 LayoutInflater。它解释了如何使用它。
  • 我正在寻找LayoutInflater的解释。
  • @Player1 可以查看this发帖
【解决方案4】:

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

基本两步:获取inflater,然后inflate资源

如何获得充气机?

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

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

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

【讨论】:

    【解决方案5】:

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

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

    这里是布局资源:

    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

    <?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"/>
    

    在 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;
    }
    

    注意不同的inflate方法调用:

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

    【讨论】:

      【解决方案6】:

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

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

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

      【讨论】:

      • 这可能是真的,但不能回答问题。
      【解决方案7】:

      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>
      

      我们可以通过静态方式显示这个布局

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

      创建视图的动态方式意味着在我们的 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>
      

      我们希望在主 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);
      

      这里我使用了 getSystemService (String) 来检索 LayoutInflater 实例。我也可以使用 getLayoutInflator() 来充气,而不是像下面这样使用 getSystemService (String):

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

      【讨论】:

        【解决方案8】:

        膨胀意味着读取描述布局(或 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);
        

        这个文件可以保存为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>
        

        这个文件可以保存为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>
        

        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();
                    }
                });
            }
        }
        

        【讨论】:

          【解决方案9】:

          充气机的作用

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

          为什么需要

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

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

          【讨论】:

          • 那么,Zahan 先生,它像 Javascript 中的 DOM 吗? •o•
          【解决方案10】:

          这里是获取布局根视图的引用的示例, 膨胀它并与 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);
          
          
          }
          

          【讨论】:

            【解决方案11】:

            Layout inflater 是一个读取 xml 外观描述并将其转换为基于 java 的 View 对象的类。

            【讨论】:

              【解决方案12】:

              LayoutInflater 基于 XML 中定义的布局创建 View 对象。使用 LayoutInflater 有多种不同的方法,包括创建自定义 View、将 Fragment 视图扩展为 Activity 视图、创建 Dialog 或简单地将布局文件 View 扩展为 Activity。

              关于通货膨胀过程的运作方式存在很多误解。我认为这来自 inflate() 方法的文档不足。如果你想详细了解 inflate() 方法,我在这里写了一篇关于它的博文:

              https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

              【讨论】:

                【解决方案13】:

                我的自定义列表希望它能说明概念

                public class second extends ListActivity {
                
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    // TODO Auto-generated method stub
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.second);
                //  TextView textview=(TextView)findViewById(R.id.textView1);
                //  textview.setText(getIntent().getExtras().getString("value"));
                
                    setListAdapter(new MyAdapter(this,R.layout.list_item,R.id.textView1, getResources().getStringArray(R.array.counteries)));
                }
                
                private class MyAdapter extends ArrayAdapter<String>{
                
                    public MyAdapter(Context context, int resource, int textViewResourceId,
                            String[] objects) {
                        super(context, resource, textViewResourceId, objects);
                        // TODO Auto-generated constructor stub
                    }
                
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                
                        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View row=inflater.inflate(R.layout.list_item,parent,false);
                        String[]items=getResources().getStringArray(R.array.counteries);
                
                        ImageView iv=(ImageView) row.findViewById(R.id.imageView1);
                        TextView tv=(TextView) row.findViewById(R.id.textView1);
                        tv.setText(items[position]);
                
                        if(items[position].equals("unitedstates")){
                            iv.setImageResource(R.drawable.usa);
                        }else   if(items[position].equals("Russia")){
                            iv.setImageResource(R.drawable.russia);
                        }else   if(items[position].equals("Japan")){
                            iv.setImageResource(R.drawable.japan);
                        }
                        // TODO Auto-generated method stub
                        return row;
                    }
                
                }
                
                }
                

                【讨论】:

                  【解决方案14】:

                  LayoutInflater 是 Android 中的一个基本组件。您必须始终使用它来将 xml 文件转换为视图层次结构。

                  【讨论】:

                    【解决方案15】:

                    Inflater 实际上是某种转换为数据、视图、实例、可见 UI 表示的方式......因此它以编程方式利用来自适配器等的数据馈送。然后将它与您定义的 xml 集成,告诉它应该如何在 UI 中表示数据

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2016-09-09
                      • 2013-07-22
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多