How to add CardView attributes to app theme?
Asked Answered
B

1

9

My question is similar to "How to put a CardView attribute in a style", but I need to go deeper.

I'm using AppCompat theme, and my styles looks like

style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/toolbar_color</item>
    <item name="android:listViewStyle">@style/CustomListView</item>
</style>

and I create separate style for CardView

<style name="CustomCardView" parent="CardView">
    <item name="cardBackgroundColor">@color/card_background</item>
    <item name="cardCornerRadius">@dimen/card_corner</item>
</style>

Can I attach it to main style?

Briarroot answered 28/4, 2015 at 8:51 Comment(1)
Please check this answer.Isa
F
5
public View(Context context, AttributeSet attrs, int defStyleAttr)

@param defStyleAttr An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.

So you have to do

attrs.xml

<attr name="myCardViewStyle"/>

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="myCardViewStyle">@style/CustomCardView</item>
</style>

<style name="CustomCardView" parent="CardView">
    <item name="cardBackgroundColor">@android:color/holo_red_dark</item>
</style>

MyCardView.java

public MyCardView(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.myCardViewStyle);
}

public MyCardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

That's it.

Funke answered 10/10, 2015 at 9:32 Comment(2)
Could you please explain where to reference the MyCardView class in Code or Style?Friedlander
@SenthilkumarS Just use it in your layout files just like any other view. <com.myapplicationpackage.views.custom.MyCardView> ...</com.myapplicationpackage.views.custom.MyCardView>Tramroad

© 2022 - 2024 — McMap. All rights reserved.