Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CardView attributes to app theme?

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?

like image 291
ITurchenko Avatar asked Apr 28 '15 08:04

ITurchenko


People also ask

How do I customize my CardView?

Customized CardView First, add a CardView dependency to the application-level build. gradle file. Then create a drawable background for the cards. For that, create a new drawable resource file inside the drawable folder.

Which attribute adds shadow to CardView?

A FrameLayout with a rounded corner background and shadow. CardView uses elevation property on Lollipop for shadows and falls back to a custom emulated shadow implementation on older platforms.

How does CardView work in Android Studio?

CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design.


1 Answers

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.

like image 117
Neil Avatar answered Oct 11 '22 18:10

Neil