CardView在充气时丢失了边距。

17
在我的活动中,我正在onCreate方法中设置activity_main的布局。然后,我希望为数组中的每个项目填充我的CardView。
到目前为止,我已经加载了所有内容,但是我的CardView失去了它们的边距。当通过XML添加到布局中时,边距起作用,但是当作为单独的XML文件填充时,边距就会丢失。
我这样填充activity_main_card:
LinearLayout item = (LinearLayout)findViewById(R.id.card_holder);
View child = getLayoutInflater().inflate(R.layout.activity_main_card, null);
item.addView(child);
在activity_main_card中,我的XML如下:
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="2dp"
    android:layout_marginBottom="16dp">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:scaleType="fitCenter"
            android:background="@drawable/cin"/>

        <LinearLayout
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:orientation="vertical"
             android:padding="16dp">

             <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:textStyle="bold"
                android:textColor="@color/dark_grey"/>

             <TextView
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:textSize="12sp"
                 android:textStyle="normal"
                 android:textColor="@color/grey_500"/>

        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>

有人能指出我错了的方向吗?

1个回答

31
你正在将null作为父ViewGroup参数传递给inflate()方法。这将导致所有layout_*属性被忽略,因为布局填充器不知道哪些属性对于将要放置的容器是有效的(即它不知道在哪个LayoutParams类型上设置View)。
View child = getLayoutInflater().inflate(R.layout.activity_main_card, null);

应该是

View child = getLayoutInflater().inflate(R.layout.activity_main_card, item, false);

想要了解更多信息,请看这篇优秀的文章 -- 这是一个常见的错误。


3
谢谢。那很有道理,然而官方文档在这方面有点令人困惑。文章也写得很好! - K20GH
运行得很好。谢谢。 - DysaniazzZ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接