setContentView、findViewById 和 inflate 的区别?

通俗的说,inflate就相当于将一个xml中定义的布局找出来.
因为在一个Activity里如果直接用findViewById()的话,对应的是setConentView()的那个layout里的组件.

因此如果你的Activity里如果用到别的layout,比如对话框上的layout,你还要设置对话框上的layout里的组件(像图片 ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,然后再用这个layout对象去找到它上面的组件,如:
View view = View.inflate(this, R.layout.dialog_layout, null);
TextView dialogTV = (TextView) view.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");

如果组件R.id.dialog_tv是对话框上的组件,而你直接用this.findViewById(R.id.dialog_tv),那么返回值将是null



三种方式可以生成LayoutInflater :
LayoutInflater inflater = LayoutInflater.from(this);
LayoutInflater inflater = getLayoutInflater();
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
然后调用inflate方法将xml布局文件转成View
public View inflate (int resource, ViewGroup root, boolean attachToRoot)

在View类中,也有inflate方法

public static View inflate (Context context, int resource, ViewGroup root)


————————————————————————————————————————————————————————


findViewById有两种形式 
R.layout.xx是引用res/layout/xx.xml的布局文件(inflate 方法),R.id.xx是引用布局文件里面的组件,组件的id是xx(findViewById方法)。

所有的组件id都能用R.id.xx来查看,但是组件不在setContentView()里面的layout中就无法使用,Activity.findViewById()会出现空指针异常 

a. activity中的findViewById(int id) 
b. View 中的findViewById(int id) 

不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。 


转载自         博主:dylgsy

                  地址http://blog.csdn.net/dylgsy/article/details/22317275

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值