android适配器,子布局不能撑满父容器

来源:互联网 发布:fcc 网络中立 编辑:程序博客网 时间:2024/05/20 23:29

最近在看View绘制的源码,以及根据xml布局生成view的源码。然后今天刚好赶上在适配器实例化ViewHoldr根据item.xml ,以前写这块代码时没注意,结果死活子布局不能撑满父容器。然后我去看源码弄明白了。

起初实例化viewholder是如下代码:

只贴部分代码:

LayoutInflater.from(mContext).inflate(viewType,null)


无论如何都不能撑满父容器,我仔细检查了xml 中宽的属性如下,丝毫没有错误。

android:layout_width="match_parent"


后来我把ViewGroup作为参数传入了inflate(viewType,parent)中然后报了一堆错我大致看了一下意思就是已经有父容器了。后来没办法了逼的我去看这句代码的源码,如下

/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }


看它的注释没看太明白接着追到了红色inflate()的重载方法。如下:


/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> is false.)
     * @param attachToRoot Whether the inflated hierarchy should be attached to
     *        the root parameter? If false, root is only used to create the
     *        correct subclass of LayoutParams for the root view in the XML.
     * @return The root View of the inflated hierarchy. If root was supplied and
     *         attachToRoot is true, this is root; otherwise it is the root of
     *         the inflated XML file.
     */
    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();
        }
    }



看到这里还是不能解决问题,接着往下看,还找红色部分代码那个方法的实现。如下:


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
                    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);
                        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.
                    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.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }


            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;


                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }


            return result;
        }
    }

代码比较多不需全部都看懂找关键的就行。我标注了一些代码有红色的有绿色的,先看红色的。

红色部分代码表达的首先是根据xml 布局生成一个view,然后就是 root !=null 并且 attachToRoot ==false 就给view设置 LayoutParams ,这下总算明白了原来是我xml布局中的参数没有被设置上去。使用inflater()的另一个重载方法可以解决这个问题。如下:

LayoutInflater.from(mContext).inflate(viewType,parent,false)

显示的问题解决了,宽能够撑满父容器了,但是那个报错的问题是怎么回事得搞明白,和绿色那行代码有关系,于是我就顺着方法的调用找到了ViewGroup中一直跟着方法的调用追到了这个方法,如下:


private void addViewInner(View child, int index, LayoutParams params,
            boolean preventRequestLayout) {
        if (mTransition != null) {
            // Don't prevent other add transitions from completing, but cancel remove
            // transitions to let them complete the process before we add to the container
            mTransition.cancel(LayoutTransition.DISAPPEARING);
        }

        if (child.getParent() != null) {
            throw new IllegalStateException("The specified child already has a parent. " +
                    "You must call removeView() on the child's parent first.");
        }
   
    }


由于方法的内容太多我删掉了其它部分。红色代码行表达的很清楚,它检查childview中是否已经有了父容器,如果有了就抛异常。其实在根据xml创建view的时候就已经把父容器指定了,所以调用root.addView(temp, params);会抛异常。

现在来总结一下:

1.item视图没有撑满父容器是传参的问题。解决:

LayoutInflater.from(mContext).inflate(viewType,parent,false)

2.抛 The specified child already has a parent 是因为addView()造成的。直接来说就是传参有问题。

 调用  inflate(viewType,parent) 会间接使 attachToRoot变为true从而调用 root.addview()这个方法从而会抛出异常。






原创粉丝点击