安卓学习之LayoutInflater

1.LayoutInflater与findViewById区别

1、LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;
对于一个没有被载入或者想要动态载入的界面,都需要使用 LayoutInflater.inflate()来载入.
2、findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等);
对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

2.获得 LayoutInflater 实例的三种方式

LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()

LayoutInflater inflater = LayoutInflater.from(context);

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

3.inflate

从指定的xml资源中填充新的视图层次结构

inflate方法一:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
inflate方法二:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                  + Integer.toHexString(resource) + ")");
        }

        View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
        if (view != null) {
            return view;
        }
        XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
4.参数详解:
resource:

要添加的布局资源文件

root:

可选视图作为生成的层次结构的父级

  • root参数null和有值时的区别:

null和有值的区别 null时第一个参数中最外层的布局大小无效,有值的时候最外层的布局大小有效

attachToroot:

是否将层次结构的布局文件添加到父视图

  • attachToRoot作用(tryInflatePrecompiled函数部分):
if (attachToRoot) {
	root.addView(view, params);
} else {
	view.setLayoutParams(params);
}

若attachToRoot为true且root不为null,则调用root.addView()方法

4.attachToRoot什么时候为true:

Adapter不能将attachToRoot参数设置为true;
在为fragment创建布局时,如果为true,那么这个布局文件就会被添加到父activity中盛放fragment的布局中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值