【发布时间】:2014-09-02 01:26:13
【问题描述】:
我有一些“卡片”,它是一个简单的 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>
然后我有一个带有垂直线性布局的主片段。在这个主片段中,我将这个“卡片”添加到主布局中:
# 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);
这很好用,而且我的卡片填满了片段布局的整个宽度。实际上是我所期待的。
现在我为我的卡片创建了一个单独的类:
Class Card extends LinearLayout{
public Card(Context context) {
super(context);
View view = LayoutInflater.from(getContext()).inflate(
R.layout.card, null);
this.addView(view);
}
}
然后,如果我将我的卡片添加到主片段布局中:
# 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());
然后它被添加但卡片的宽度不再填充,而是包装到文本视图。
谁能解释一下为什么我通过这两种添加相同布局的方法得到不同的宽度尺寸?
解决方案这里是改变 Card 类来解决这个问题:
public Card(Context context) {
super(context);
LayoutInflater.from(getContext()).inflate(
R.layout.card, this);
}
}
【问题讨论】:
-
你确定你的
Card改变了宽度而不是LinearLayout? -
是的。我简化了问题以便更好地理解,因为我正在处理更复杂的事情。但问题是,将“卡片”直接添加到布局中并通过新类 - 给出不同的结果。我假设通过新类添加父布局宽度无法以某种方式验证。
标签: android android-layout android-fragments android-linearlayout android-context