我在我的XML布局中有一个CardView
,我需要通过编程的方式设置它的边距(因为我并不总是需要边距。根据一些条件,我要么设置或删除边距)。
这是我的做法:
CardView.LayoutParams layoutParams = (CardView.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
这个很好用。它在我的CardView
底部加上了2dp
的边距。但是,在我的日志中,我得到了以下信息:
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
所以我将 CardView.LayoutParams
改成了 FrameLayout.LayoutParams
,像这样:
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
然而,它再次起作用了,但我收到了与上述相同的错误。
所以我再次修改它,使用 LinearLayout.LayoutParams
。
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
当我这样做时,我没有收到错误信息,但是它没有设置任何边距。我应该忽略这个错误吗?这似乎不太对。编辑:这是我的 XML 中的 CardView:<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:background="@android:color/white"
android:minHeight="@dimen/item_min_height"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="@+id/cardViewAppointmentWeek"
app:cardElevation="2dp"
android:layout_marginBottom="2dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:background="?android:attr/selectableItemBackground"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
CardView
。 - ᴛʜᴇᴘᴀᴛᴇʟCardView
的直接父视图是什么? - azizbekianLinearLayout
。我已经更新了我的问题,这样你就可以看到我的布局。 - ᴛʜᴇᴘᴀᴛᴇʟ