了解LayoutInflater,了解Android视图基础

1. LayoutInflater有什么用

可以将一个Layout文档(Android中使用XML文档来描述一个Layout)实例化为一个View的实例。

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

一个最简单的应用例子。我们在创建一个Activity的时候,一般会为该Activity设定一个内容视图,如 setContentView(R.layout.main)

 

我们可以看看setContentView的文档:

 

void android.app.Activity.setContentView(int layoutResID)

 

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views  to the activity. Parameters layoutResID Resource ID to be inflated. 

意思是我们设定内容视图时,实际就是inflate了一个layout文件。即如上所说,将XML文档实例化为一个View的实例(Layout中描述的所有控件都会被实例化为View,一般返回的是Root View,就是最根本的View句柄)。

 

2. LayoutInflater与findViewById的区别

实际上弄清楚了setContentView做的事情,就比较容易理解两者的区别。

findViewById是用来查找当前Activity对应layout中的某项View,使用了R.Id.XXX作为参数来索引。也就是说,要先inflate了一个layout,再用findViewById来找layout实例中的某项View。

再具体一点,setContentView实例化了一个layout(当然也可以用LayoutInflater.inflate())来做),findViewById找其中的某项View。

 

 

View android.app.Activity.findViewById(int id)

 

Finds a view that was identified by the id attribute from the XML that was processed in onCreate (Bundle). Returns the view if found or null otherwise.

 

以上除去标注为引用的部分,其余为自己组织的语言。

如果需要实例,可以参考http://shazhuzhu1.iteye.com/blog/985815


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值