我的 XML 布局中有一个CardView
,我需要以编程方式为其设置边距(这是因为我始终不需要边距。根据少数条件,我设置或删除边距)。
我是这样做的:
CardView.LayoutParams layoutParams = (CardView.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
这工作得很好。它把2dp
边距放在我的底部CardView
。但是,我在我的 logcat 中得到了这个:
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);
当我这样做时,我没有收到错误,但它没有设置任何边距。
我应该忽略错误吗?只是看起来不太对。
编辑:
这是我CardView
的XML:
<?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>