【问题标题】:CardView has lost margin when inflatingCardView 在充气时失去了保证金
【发布时间】:2014-09-03 05:45:08
【问题描述】:

在我的活动中,我正在设置布局 activity_main onCreate。然后我想为我的数组中的每个项目扩展我的 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>

谁能指出我出错的方向?

【问题讨论】:

    标签: android xml


    【解决方案1】:

    您将null 作为父ViewGroup 参数传递给inflate()。这将导致所有layout_* 属性被忽略,因为充气机不知道哪些属性对于将要放置的容器有效(即它不知道在View 上设置哪个LayoutParams 类型) .

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

    应该是

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

    有关详细信息,请参阅 this great article 了解它 - 这是一个常见错误。

    【讨论】:

    • 谢谢。这是有道理的,但是官方文档在这方面有点令人困惑。文章也不错!
    • 像魅力一样工作。谢谢。
    猜你喜欢
    • 2013-03-26
    • 2011-04-19
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多