I'm trying to create a CardView
from code. However, it does not seem to apply the style correctly. Here are the styles:
<style name="CardViewStyle" parent="CardView">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_margin">8dp</item>
</style>
<style name="Widget.CardContent" parent="android:Widget">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:paddingLeft">16dp</item>
<item name="android:paddingRight">16dp</item>
<item name="android:paddingTop">24dp</item>
<item name="android:paddingBottom">24dp</item>
<item name="android:orientation">vertical</item>
</style>
In XML, it would look like this:
<android.support.v7.widget.CardView
style="@style/CardViewStyle">
<LinearLayout
style="@style/Widget.CardContent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textAppearance="@style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Caption"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Now I'm trying to do the exact same in Java:
CardView card = new CardView(new ContextThemeWrapper(MyActivity.this, R.style.CardViewStyle), null, 0);
LinearLayout cardInner = new LinearLayout(new ContextThemeWrapper(MyActivity.this, R.style.Widget_CardContent));
TextView tv_title = new TextView(this);
tv_title.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
));
tv_title.setTextAppearance(this, R.style.TextAppearance_AppCompat_Title);
tv_title.setText("Name");
TextView tv_caption = new TextView(this);
tv_caption.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
));
tv_caption.setText("Sus");
cardInner.addView(tv_title);
cardInner.addView(tv_caption);
Here are the results. In this image, the first CardView is created by XML. The second CardView is created programmatically. It seems that the second one does not apply parent="CardView"
only, as the other properties (layout_width, layout_height, layout_margin) are correctly applied.
For some reason, setting the margin makes the whole thing work again.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
int margin = dpToPixel(8);
params.setMargins(margin, margin, margin, margin);
card.setLayoutParams(params);
I had a similar issue and this helped me: CardView has lost margin when inflating
I was passing null
as the CardView's parent to View.inflate()
, which meant that the xml layout_marginLeft
etc parameters were being ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With