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

最近在看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()这个方法从而会抛出异常。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,图片适配器通常用于在列表视图、网格视图或翻页视图等容器中显示图片。适配器负责将图片数据绑定到每个视图中,以便正确显示图片。 以下是一个简单的图片适配器示例: ```java public class ImageAdapter extends BaseAdapter { private Context mContext; private int[] mImageIds; public ImageAdapter(Context context, int[] imageIds) { mContext = context; mImageIds = imageIds; } public int getCount() { return mImageIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // 如果没有可重用的视图,则创建一个新的ImageView imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(100, 100)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); } else { // 如果有可重用的视图,则使用它 imageView = (ImageView) convertView; } // 加载图片 imageView.setImageResource(mImageIds[position]); return imageView; } } ``` 在上面的示例中,`ImageAdapter` 继承自 `BaseAdapter` 类,该类是 Android适配器的基类。在构造函数中,传入了一个 `Context` 对象和一个图片 ID 数组,用于初始化适配器。`getCount` 方法返回图片 ID 数组的长度,`getItem` 和 `getItemId` 方法不需要实现,因为它们不会被使用。`getView` 方法是适配器最重要的方法,用于创建或重用视图,并将图片数据绑定到视图中。在该方法中,首先检查是否存在可重用的视图,如果没有,则创建一个新的 `ImageView` 对象,并设置其布局参数和缩放类型。然后,加载并显示适当位置的图片。 请注意,上面的代码中,图片的大小是硬编码的。为了实现更好的图片适配,应该使用 Android 提供的不同尺寸的资源文件夹来存储不同分辨率的图片,例如: ``` res/drawable-mdpi/my_image.png res/drawable-hdpi/my_image.png res/drawable-xhdpi/my_image.png res/drawable-xxhdpi/my_image.png ``` 在加载图片时,适配器将自动根据设备的屏幕密度选择正确的图片。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值