我有一些“卡片”,它是一个简单的 LinearLayout,里面有一个 TextView
<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>
然后我有一个带有垂直线性布局的主 fragment 。在这个主 fragment 中,我将这个“卡片”添加到主布局中:
# 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);
这很好用,而且我的卡片填满了 fragment 布局的整个宽度。实际上是我所期待的。
现在我为我的卡片创建了一个单独的类:
Class Card extends LinearLayout{
public Card(Context context) {
super(context);
View view = LayoutInflater.from(getContext()).inflate(
R.layout.card, null);
this.addView(view);
}
}
然后,如果我将我的卡片添加到主 fragment 布局中:
# 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 。
谁能解释一下为什么我通过这两种添加相同布局的方法得到不同的宽度尺寸?
解决方案这里是改变 Card 类来解决这个问题:
public Card(Context context) {
super(context);
LayoutInflater.from(getContext()).inflate(
R.layout.card, this);
}
}
最佳答案
这不是实现自定义 View 类的正确方法。在您的 Card 类的实现中,您实际上是在创建一个不需要的额外 LinearLayout。
首先,实现扩展 LinearLayout 的 Card 类。然后,在您的 XML 布局中引用它,如下所示:
<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>
关于android - 如何正确扩展 LinearLayout 以创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24697405/