android layoutinflater 参数

LayoutInflater.from(Context context),这里调用时传入getApplicationContext()某个Activity.this时效果不同。

    public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

它调用了Context.getSystemService这个方法,然而该方法在activity的父类ContextThemeWrapper中被重写了:

 @Override public Object getSystemService(String name) {
        if (LAYOUT_INFLATER_SERVICE.equals(name)) {
            if (mInflater == null) {
                mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
            }
            return mInflater;
        }
        return getBaseContext().getSystemService(name);
    }

因而传入Activity对象作context参数时,还能获取该activity的主题等属性,从而使得LayoutInflater的inflate方法返回的View可能有所不同。



另外inflate方法的root参数,不为null时,意思是设定root为该布局的父控件/布局,然后即可根据父布局计算该布局长宽等属性;attachToRoot默认为真,作用为添加当前布局到父布局,相当于省去父布局addView()这步而已;为false时,不自动添加到父布局。为null时,无视attachToRoot,采用默认计算方法计算该布局。

注意:用ListView等时,Adapter的getView中root需要填null,因为setAdapter()方法会自动把view挂到ListVIew下。即不填null将可能导致重复挂到ListView上而出差。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容