我在我的XML佈局中有一個CardView
,我需要以編程方式爲它設置邊距(這是因爲我不需要任何時間保證金,基於很少的條件,我可以設置或刪除保證金)。以編程方式設置邊距到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);
當我這樣做,我不明白的錯誤但是它不設置任何保證金。
如果我只是忽略這個錯誤嗎?這看起來不正確。
編輯:
這是我在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>
你能告訴我你的XML代碼cardview? – redAllocator
@red_allocator我已更新我的問題以顯示xml中的'CardView' –
誰是你的'CardView'的直接父母? – azizbekian