Creating CardView programmatically doesn't match style correctly

I am trying to create CardView code from code. However, it does not seem to fit the style. 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 will 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 am trying to do the 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 does not apply only parent="CardView" , as other properties (layout_width, layout_height, layout_margin) are correctly applied.

+5
source share
2 answers

For some reason, setting the field makes everything 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); 
+7
source

I had a similar problem and it helped me: CardView lost the bloat advantage

I passed null as the parent of CardView to View.inflate() , which meant that the parameters were xml layout_marginLeft , etc. ignored.

+1
source

All Articles