Android 三种布局填充方式

2018-02-07  本文已影响0人  我是你森哥哥

1. 布局填充方式

        //[1]获取打气筒 服务器第一种方式
        view = View.inflate(getApplicationContext(), R.layout.item, null);

        //[2]布局的填充器第二种写法
        LayoutInflater layoutInflater = LayoutInflater.from(getApplicationContext());
        layoutInflater.inflate(R.layout.item, null, true);

        //[3]获取布局填充器 第三种写法 获取一个系统的服务  (布局填充器的服务 )
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item, null,true);

    }

2. View.inflate() 方法最终也是调用LayoutInflater.inflate() 方法

lALPBbCc1y8a9_LNASDNA8w_972_288.png
    /**
     * View.inflate() 方法最终也是调用LayoutInflater.inflate() 方法
     */
    /**
     *
     * @param context   上下文
     * @param resource  要填充的xml资源
     * @param root      填充成的view对象的根布局
     * @return
     */
    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

3. LayoutInflater.inflate() 方法


    /**
     *
     * @param resource   要填充的xml文件
     * @param root       生成的view对象的父控件。同样该参数可以为null。若提供了root,则返回root作为根布局,否则,返回填充出的view对象的根布局作为根布局。
     * @return
     */
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
    
    
    LayoutInflater.inflate()方法,三个构造参数

    /**
     *说明:第一个参数不需多说,我们一般就从resource目录下找到我们要填充的布局文件即可,切不可用普通的xml文件进行填充,除非我们自己做好了相应的xmlpullparser。
     若第二个参数为null,也就是我们不指定父控件,那么新生产的view对象的根布局的某些参数会失效,比如Layout_width和Layout_height会失效,这个大家可以做实验尝试,无论第三个参数是什么。
     * 
     * @param resource      就是我们要填充的xml文件
     * @param root          这个要和第三个参数有关系,大家慢慢看。若是第三个参数为true,那么第二个参数的意义是,从第一个参数填充成的view对象的父控件;若是第三个参数为false,那么第二个参数的意义是,可以为第一个参数生成的view对象的根布局提供一系LayoutParams参数的控件。
     * @param attachToRoot  从第一个参数填充成的view对象是否要附着到第二个参数指定的空间上作为子控件。
     * @return
     */
    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) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

上一篇 下一篇

猜你喜欢

热点阅读