Ich versuche, eine CardView
aus Code zu erstellen. Es scheint jedoch, den Stil nicht korrekt anzuwenden. Hier sind die Stile:Das Erstellen eines CardView programmgesteuert nicht ordnungsgemäß angewendet
<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, es würde wie folgt aussehen:
<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>
Jetzt versuche ich genau das gleiche in Java zu tun:
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);
Hier sind die Ergebnisse. In diesem Bild wird das erste CardView durch XML erstellt. Das zweite CardView wird programmgesteuert erstellt. Es scheint, dass der zweite nur auf parent="CardView"
angewendet wird, da die anderen Eigenschaften (layout_width, layout_height, layout_margin) korrekt angewendet werden.
Eine Empfehlung einer ähnlichen SO-Antwort wäre besser als Kommentar. Wenn die _questions_ ** Duplikate ** sind, sollte der eine oder der andere zum Schließen als solcher gekennzeichnet werden. – Mogsdad