J'ai ma CardView
dans ma mise en page XML et j'ai besoin de lui attribuer des marges par programme (car je n'ai pas besoin de marge à tout moment. marge).Définition de la marge par programme à CardView
Voici comment je l'ai fait:
CardView.LayoutParams layoutParams = (CardView.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
Cela a bien fonctionné. Il a mis 2dp
marge au bas de mon CardView
. Cependant, je reçois dans mon logcat:
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams
Je changé CardView.LayoutParams
à FrameLayout.LayoutParams
, comme ceci:
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
Et encore une fois, cela fonctionne, mais je reçois la même erreur que ci-dessus. J'ai donc modifié une fois de plus pour utiliser LinearLayout.LayoutParams
.
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.setLayoutParams(layoutParams);
Quand je fais cela, je ne suis pas l'erreur mais il ne fixe aucune marge.
Dois-je simplement ignorer l'erreur? Cela ne semble pas juste.
EDIT:
Voici mon CardView
en 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>
Pourriez-vous me montrer le dans votre code Vignettes xml? – redAllocator
@red_allocator J'ai mis à jour ma question pour montrer le 'CardView' en xml –
Qui est le parent direct de votre' CardView'? – azizbekian