在Android中LayoutInflater的用途是什么?


当前回答

充气机的作用

它接受一个xml布局作为输入(比如说)并将其转换为视图对象。

为什么需要

让我们设想一个场景,我们需要创建一个自定义列表视图。现在每一行都是自定义的。但是我们怎么做呢?不可能将xml布局分配给列表视图的一行。我们创建了一个View对象。因此,我们可以访问其中的元素(textview,imageview等),也分配对象作为列表视图行

无论何时我们需要在某处分配视图类型对象我们有自定义xml设计我们只需将它转换为object by inflater并使用它。

其他回答

下面是一个示例,用于获取布局的根视图的引用, 膨胀它并使用setContentView(视图视图)

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


}

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

在官方文档中阅读更多信息。

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

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

基本的两个步骤:获取膨胀器,然后对资源进行膨胀

你怎么拿到充气机?

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

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

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

充气机的作用

它接受一个xml布局作为输入(比如说)并将其转换为视图对象。

为什么需要

让我们设想一个场景,我们需要创建一个自定义列表视图。现在每一行都是自定义的。但是我们怎么做呢?不可能将xml布局分配给列表视图的一行。我们创建了一个View对象。因此,我们可以访问其中的元素(textview,imageview等),也分配对象作为列表视图行

无论何时我们需要在某处分配视图类型对象我们有自定义xml设计我们只需将它转换为object by inflater并使用它。