[英]How do you set the layout width of a cardview inside a linearlayout programmatically?
I am trying to change the layout width of two cardview element between MATCH_PARENT and 0dp. 我正在尝试在MATCH_PARENT和0dp之间更改两个cardview元素的布局宽度。 When I simulate the scenario via xml changes, it is correct, however, when I do it programmatically, it is not rendering as expected.
当我通过xml更改模拟场景时,它是正确的,但是,当我以编程方式进行操作时,它并没有按预期方式呈现。
xml XML文件
<LinearLayout
android:id="@+id/lDates"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/card_margins"
android:layout_marginEnd="@dimen/card_margins"
android:layout_below="@id/lnrButtons"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:id="@+id/cardSectionA"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:cardElevation="0dp"
android:layout_marginEnd="@dimen/card_margins"
android:layout_marginBottom="@dimen/card_margins"
app:cardCornerRadius="4dp"
android:layout_weight="1">
<TextView
android:id="@+id/textLabelA"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/sample_value"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/cardSectionB"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:cardElevation="0dp"
android:layout_marginEnd="@dimen/card_margins"
android:layout_marginBottom="@dimen/card_margins"
app:cardCornerRadius="4dp"
android:layout_weight="1">
<TextView
android:id="@+id/textLabelB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sample_value"/>
</android.support.v7.widget.CardView>
</LinearLayout>
java 爪哇
//as-is scenario; cardSectionA and cardSectionB should be shown
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
cardSectionA.getLayoutParams().width,
LinearLayout.LayoutParams.WRAP_CONTENT
);
cardSectionA.setLayoutParams(params);
cardSectionB.setLayoutParams(params);
//should only show cardSectionA scenario
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
cardSectionA.setLayoutParams(params);
Thanks a lot. 非常感谢。
Figured it out. 弄清楚了。 To behave as expected, the margin and layout weight must also be set.
为了达到预期效果,还必须设置边距和布局权重。
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
int margin = 10;
params.setMargins(margin, margin, margin, margin);
params.weight = 1;
cardSectionA.setLayoutParams(params);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.