美文网首页
android layoutinflater 参数

android layoutinflater 参数

作者: codeflame | 来源:发表于2018-07-31 11:38 被阅读0次

    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上而出差。

    相关文章

      网友评论

          本文标题:android layoutinflater 参数

          本文链接:https://www.haomeiwen.com/subject/toicvftx.html