当前位置: 移动技术网 > IT编程>移动开发>Android > Android getViewById和getLayoutInflater().inflate()的详解及比较

Android getViewById和getLayoutInflater().inflate()的详解及比较

2019年07月24日  | 移动技术网IT编程  | 我要评论

军少的野蛮小娇妻,天津青年旅行社,信阳毛尖价格

android getviewbyid和getlayoutinflater().inflate()的详解及比较

               由于本人刚刚学习android 对于getviewbyid和getlayoutinflater().inflate()的方法该如何使用不知如何分别,这里就上网查下资料整理下,大家可以看下。

layoutinflater

要明白这个问题首先要知道什么是layoutinflater。根据android的官方api解释:

instantiates a layout xml file into its corresponding view objects.

由此可知,这个类是用来根据xml布局文件来实例化相应的view的。

getlayoutinflater()

根据api的文档解释,定义后面紧接着一句:

it is never used directly.

由此可知,layoutinflater不能直接使用,即不能使用new来初始化。同时根据定义可以看出在实际开发中layoutinflater这个类还是非常有用的,比如对于一个没有被载入或者想要动态载入的界面,都需要使用layoutinflater.inflate() 来载入。

既然很有用,又不能直接初始化,肯定会有其他的方式获得layoutinflater的实例。一般获得 layoutinflater 有实例的三种方式:

 1. layoutinflater inflater = getlayoutinflater(); //调用activity的getlayoutinflater()
 2. layoutinflater localinflater =(layoutinflater)context.getsystemservice(context.layout_inflater_service);
 3. layoutinflater inflater = layoutinflater.from(context);

如果去看源码的话,其实这三种方式本质是相同的:

activity 的 getlayoutinflater() 方法是调用 phonewindow 的getlayoutinflater()方法。

public phonewindow(context context) { 
  super(context); 
  mlayoutinflater = layoutinflater.from(context); 
}

可以看出它其实是调用 layoutinflater.from(context)。

layoutinflater.from(context):

public static layoutinflater from(context context) { 
  layoutinflater layoutinflater = (layoutinflater) context.getsystemservice(context.layout_inflater_service); 
  if (layoutinflater == null) { 
    thrownew assertionerror("layoutinflater not found."); 
  } 
  return layoutinflater; 
}

可以看出它其实调用 context.getsystemservice()。

结论:所以这三种方式最终本质是都是调用的context.getsystemservice()。

inflate()

inflate 方法 通过 sdk 的 api文档可知:

inflate a new view hierarchy from the specified xml resource.

即inflater() 是用来找 xml 布局文件,并且实例化成view 对象。

layoutinflater inflater = (layoutinflater)getsystemservice(layout_inflater_service); 
view view = inflater.inflate(r.layout.custom, (viewgroup)findviewbyid(r.id.test)); 
edittext edittext = (edittext)view.findviewbyid(r.id.content);

getviewbyid()

getviewbyid()应该熟悉的,刚接触android时最先接触到的几个方法里肯定有他。findviewbyid()是找xml布局文件下的具体widget控件(如button、textview等)。

最后说一句,对于一个没有被载入或者想要动态载入的界面,都需要使用layoutinflater.inflate(),getlayoutinflater()返回layoutinflater实例,所以,可以说getlayoutinflater().inflater() 是用来找 res/layout下的 xml 布局文件,并且实例化;findviewbyid() 是找具体 xml 布局文件中的具体 widget 控件(如:button、textview 等)。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网