LayoutInflater源码分析之Inflate

来源:互联网 发布:最好的电子狗软件 编辑:程序博客网 时间:2024/05/20 07:18
今天在自己使用RecyclerView的时候出现了一些小Bug,然后自己就编写了一些测试代码进行分析,这里就拿出来跟大家分享一下。

问题的出现我会在代码中标识出:

MainActivity.java:

public class MainActivity extends AppCompatActivity {    private RecyclerView recyclerView;    private List<String> mDatas;    private HomeAdpater homeAdpater;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);        initData();        homeAdpater = new HomeAdpater(MainActivity.this, mDatas);        recyclerView.setLayoutManager(new LinearLayoutManager(this));        recyclerView.setAdapter(homeAdpater);    }    protected void initData() {        mDatas = new ArrayList<String>();        for (int i = 'A'; i < 'z'; i++) {            mDatas.add("" + (char) i);        }   

HomeAdpater:

public class HomeAdpater extends RecyclerView.Adapter<HomeAdpater.MyViewHolder> {    Context mContext;    List<String> mDatas;    public HomeAdpater(Context context, List<String> Datas) {        this.mContext = context;        this.mDatas = Datas;    }    @Override    public HomeAdpater.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {       //list_item为没有父布局包裹的        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);//成功        //View view = View.inflate(mContext,R.layout.list_item,null);   //可以显示但LayoutParams == null(失效)        //View view = View.inflate(mContext,R.layout.list_item,parent);    //显示已经有一个paraent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, true);//显示已经有一个parent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null, true);//可以显示但是布局item的布局效果失效        //list_item有父布局包裹的        // View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);//成功        //View view = View.inflate(mContext,R.layout.list_item,null);//可以显示但LayoutParams!=null,但是布局item的布局效果失效        //View view = View.inflate(mContext,R.layout.list_item,parent);//显示已经有一个paraent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, true);//显示已经有一个parent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null, true);//可以显示但是布局item的布局效果失效        MyViewHolder holder = new MyViewHolder(view);        return holder;    }    @Override    public void onBindViewHolder(HomeAdpater.MyViewHolder holder, int position) {        holder.tv.setText(mDatas.get(position));        ViewGroup.LayoutParams params = holder.tv.getLayoutParams();        if (params == null) {            System.out.println("params" + params);        } else {            System.out.println("params!=" + params);        }    }    @Override    public int getItemCount() {        return mDatas.size();    }    class MyViewHolder extends RecyclerView.ViewHolder {        TextView tv;        public MyViewHolder(View view) {            super(view);            tv = (TextView) view.findViewById(R.id.id_num);        }    }}

这里存在着两种布局,一种是布局内本身就有父容器,另一种是没有父容器的。

list_item.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:background="#44ff0000"android:layout_height="wrap_content" ><TextViewandroid:id="@+id/id_num"android:layout_width="match_parent"android:layout_height="50dp"android:gravity="center"android:text="1" /></LinearLayout>

list_item.xml<?xml version="1.0" encoding="utf-8"?><TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/id_num"android:layout_width="match_parent"android:layout_height="50dp"android:gravity="center"android:text="1" />

问题:

//list_item为没有父布局包裹的        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);//成功        //View view = View.inflate(mContext,R.layout.list_item,null);   //可以显示但LayoutParams == null(失效)        //View view = View.inflate(mContext,R.layout.list_item,parent);    //显示已经有一个paraent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, true);//显示已经有一个parent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null, true);//可以显示但是布局item的布局效果失效        //list_item有父布局包裹的        // View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);//成功        //View view = View.inflate(mContext,R.layout.list_item,null);//可以显示但LayoutParams!=null,但是布局item的布局效果失效        //View view = View.inflate(mContext,R.layout.list_item,parent);//显示已经有一个paraent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, true);//显示已经有一个parent        //View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, null, true);//可以显示但是布局item的布局效果失效

为什么会出现上述的问题呢?

以上的这几种加载布局的方式默认都是去调用三个参数的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) + ")");        }        final XmlResourceParser parser = res.getLayout(resource);        try {            return inflate(parser, root, attachToRoot);//重点        } finally {            parser.close();        }    }

我们来看其中的inflate(parser, root, attachToRoot)源码:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {        synchronized (mConstructorArgs) {            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");            final Context inflaterContext = mContext;            final AttributeSet attrs = Xml.asAttributeSet(parser);            Context lastContext = (Context) mConstructorArgs[0];            mConstructorArgs[0] = inflaterContext;            View result = root;            try {                // Look for the root node.                int type;                while ((type = parser.next()) != XmlPullParser.START_TAG &&                        type != XmlPullParser.END_DOCUMENT) {                    // Empty                }                if (type != XmlPullParser.START_TAG) {                    throw new InflateException(parser.getPositionDescription()                            + ": No start tag found!");                }                final String name = parser.getName();                                if (DEBUG) {                    System.out.println("**************************");                    System.out.println("Creating root view: "                            + name);                    System.out.println("**************************");                }                if (TAG_MERGE.equals(name)) {                    if (root == null || !attachToRoot) {                        throw new InflateException("<merge /> can be used only with a valid "                                + "ViewGroup root and attachToRoot=true");                    }//解析布局                    rInflate(parser, root, inflaterContext, attrs, false);                } else {                    // Temp is the root view that was found in the xml//根据节点名来创建View对象                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);                    ViewGroup.LayoutParams params = null;                    if (root != null) {                        if (DEBUG) {                            System.out.println("Creating params from root: " +                                    root);                        }                        // Create layout params that match root, if supplied                        params = root.generateLayoutParams(attrs);//如果root不为空,并且attachToRoot为false的时候,给item布局文件中的布局参数设置起作用//否则就会出现LayoutParams为空(上述textview没有父容器,导致textview的layout_width等依赖父容器的属性失效)//(假如上述textview有父容器,则textview属性会生效,layoutParams不为空,但相应的父容器的属性会失效)//所以假如要让布局的属性显示没有问题,就必须要让root!=null&&attachToRoot=false,要不然会出现问题。//实际上 params作用就是用来让item布局内的Layout相关的属性起作用                        if (!attachToRoot) {                            // Set the layout params for temp if we are not                            // attaching. (If we are, we use addView, below)                            temp.setLayoutParams(params);                        }                    }                    if (DEBUG) {                        System.out.println("-----> start inflating children");                    }                    // Inflate all children under temp against its context.                    rInflateChildren(parser, temp, attrs, true);                    if (DEBUG) {                        System.out.println("-----> done inflating children");                    }                    // We are supposed to attach all the views we found (int temp)                    // to root. Do that now.//如果传进来的参数是有root,并且attachRoot为true,就将此item布局添加到root中,最后返回根布局//但是由于recyclerview会自动将child添加到布局当中,所以会出现"布局已经有一个parent".                    if (root != null && attachToRoot) {                        root.addView(temp, params);                    }                    // Decide whether to return the root that was passed in or the                    // top view found in xml.//如果root为空或者attachRoot为false时,就直接返回item布局view                    if (root == null || !attachToRoot) {                        result = temp;                    }                }            } catch (XmlPullParserException e) {                InflateException ex = new InflateException(e.getMessage());                ex.initCause(e);                throw ex;            } catch (Exception e) {                InflateException ex = new InflateException(                        parser.getPositionDescription()                                + ": " + e.getMessage());                ex.initCause(e);                throw ex;            } finally {                // Don't retain static reference on context.                mConstructorArgs[0] = lastContext;                mConstructorArgs[1] = null;            }            Trace.traceEnd(Trace.TRACE_TAG_VIEW);            return result;        }    }

源码总结:(借用郭神的描述)
1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义,并且item布局中的最外层布局属性将失效
2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root,对于    listview/recyclerView这种会自动将child添加到父布局中的,需要将attachToRoot置为false;
3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时, 这些layout属性会自动生效。
4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

总结:
具体解决办法:
对于这种listview与recyclerview最终解决方法:
View view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);//成功
不管是对于本身有父布局或者没有父布局都能起到很好的效果,但是只能是在使用那种默认会将child添加到
父布局当中的viewGroup.
其他:
对于其他的应用场景,只要你知道了以上所说的原理,可以适当调整参数,来设置。


0 0
原创粉丝点击