如何根据上下文获取布局Inflater?

Edw*_*Lee 218 android listview listadapter

我正在编写ListAdapter的自定义实现.

在它的构造函数中,我接受一个Context,一个资源ID(即代表布局文件的R.id.xxx),一个列表和一个map(这些包含数据).

现在,问题是我需要一个LayoutInflater来获取View对象,该对象位于单独的布局XML文件中.

如果只给出Context,我怎样才能获得LayoutInflater?

现在,为什么我认为这是可能的,这与传递给ArrayAdapter的构造函数(context,resource,textViewResourceId,data array)非常相似,我认为ArrayAdapter也必须使用LayoutInflater只给出了一个Context.

但怎么办呢?

Dav*_*ebb 503

您可以使用该类中static from()方法LayoutInflater:

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

  • 谢谢!我试图找到Context.getSomething().getAnotherThing().getLayoutInflater()! (11认同)
  • 每次需要时都需要昂贵的费用,这意味着,你认为我们应该拯救一个inflater成员吗? (4认同)
  • 哪个更好 - 一个有**270**票或一个有**25 +**票 (3认同)

Ngu*_*Dat 53

您还可以使用此代码来获取LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
Run Code Online (Sandbox Code Playgroud)

  • LayoutInflater.from(Context ctx)和this getSustemService(...)之间有什么区别? (39认同)
  • 如果inflater无法被检索,LayoutInflater.from(context)也会抛出错误:这里代码:public static LayoutInflater from(Context context){LayoutInflater LayoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if(LayoutInflater == null){throw new AssertionError("找不到LayoutInflater."); }返回LayoutInflater; } (11认同)
  • +1,好的问题,在实现方法LayoutInflater.from(context)时也调用context.getSystemService()从System Manager获取LayoutInflater Service Provider.因此可能在调用堆栈中存在垃圾差异. (8认同)