问题描述
我有一些卡片",它是一个简单的LinearLayout,里面有一个TextView
I have some "card", which is a simple LinearLayout with a TextView inside
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/card_label_txt"
android:layout_width="wrap_content"
android:text="label" />
</LinearLayout>
然后我有一个带有垂直LinearLayout的主片段..在这个主片段中,我将此卡片"添加到主布局中:
then I have my Main Fragment with a vertical LinearLayout.. and in this main fragment I add this "cards" to the main layout:
# main fragment layout
View view = inflater.inflate(R.layout.main_activity, null);
LinearLayout ll = (LinearLayout) view
.findViewById(R.id.main_activity_ll);
# get card
View card = inflater.inflate(R.layout.card, null);
# add to fragment layout
ll.addView(card);
这很好用,并且我的卡填满了片段布局的整个宽度.实际上是我所期望的.
this works very good AND my card fills the whole width of fragment layout. Actually what I am expecting.
现在我为我的卡创建了一个单独的类:
Now I created a separate Class for my Card:
Class Card extends LinearLayout{
public Card(Context context) {
super(context);
View view = LayoutInflater.from(getContext()).inflate(
R.layout.card, null);
this.addView(view);
}
}
然后,如果我以下列方式将卡添加到主要片段布局中:
And, then if I add my card to the main fragment layout in the way:
# main fragment layout
View view = inflater.inflate(R.layout.main_activity, null);
LinearLayout ll = (LinearLayout) view
.findViewById(R.id.main_activity_ll);
# add new Card to fragment layout
ll.addView(new Card(getActivity());
然后将其添加,但不再填充卡的宽度,而是将其包裹到textview中.
then it is added BUT the width of the card is no more filled, but wraped to the textview.
有人可以解释一下为什么通过这两种添加相同布局的方法获得不同的宽度大小吗?
Could someone please explain me why I get different width sizes by this two method of adding same layouts?
解决方案,此处更改了解决此问题的卡类:
Solution here is changed Card class that solves this issue:
public Card(Context context) {
super(context);
LayoutInflater.from(getContext()).inflate(
R.layout.card, this);
}
}
推荐答案
那不是实现自定义View类的正确方法.在Card类的实现中,实际上是在创建不需要的其他LinearLayout.
That isn't the correct way to implement a custom View class. In your implementation of the Card class, you're actually creating an additional LinearLayout that is not needed.
首先,实现扩展LinearLayout的Card类.然后,在您的XML布局中引用它,如下所示:
First, implement your Card class that extends LinearLayout. Then, reference it in your XML layout like such:
<com.mypackagename.Card xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/card_label_txt"
android:layout_width="wrap_content"
android:text="label" />
</com.mypackagename.Card>
这篇关于如何正确扩展LinearLayout以创建自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!