充气时,CardView的利润损失了 [英] CardView has lost margin when inflating
问题描述
在我的活动中,我将布局activity_main设置为onCreate.然后,我想为数组中的每个项目添加CardView.
In my activity, I am setting the layout activity_main onCreate. I am then wanting to inflate my CardView for each of the items in my array.
到目前为止,我已经加载了所有内容,但是我的CardView失去了利润.通过XML添加到布局中时,可以使用边距,但是当其作为单独的XML文件膨胀时,将丢失边距.
So far, I've got everything loaded, however my CardView's have lost their margin. When added to the layout through XML, the margin works, but when its inflated as a separate XML file the margin is lost.
我正在像这样夸大activity_main_card:
I am inflating the activity_main_card like so:
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如下:
In the activity_main_card, my XML is as follows:
<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>
有人可以指出我要去哪里的方向吗?
Can anyone point me in the direction where I am going wrong?
推荐答案
您要将null
作为父级ViewGroup
参数传递给inflate()
.这将导致所有layout_*
属性都将被忽略,因为充气机不知道哪些属性对将放置该容器的容器有效(即,不知道在View
上设置哪种LayoutParams
类型).
You're passing in null
as the parent ViewGroup
parameter to inflate()
. This will cause all layout_*
attributes to be ignored, as the inflater has no idea which attributes are valid for the container in which it will be placed (i.e. it has no idea which LayoutParams
type to set on the View
).
View child = getLayoutInflater().inflate(R.layout.activity_main_card, null);
应该是
View child = getLayoutInflater().inflate(R.layout.activity_main_card, item, false);
有关更多信息,请参见这篇很棒的文章-这是一篇常见错误.
For more info, see this great article about it -- it's a common mistake.
这篇关于充气时,CardView的利润损失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!