danijoo
danijoo

Reputation: 2843

Set style programmatically does not work?

This is the code of a compound view I wrote. It uses android.support.v7.widget.CardView as parent class:

public class ItemListItem extends CardView {

    TextView tvName;
    ImageView ivIcon;

    public ItemListItem(Context context) {
        super(context, null, R.style.GreenCardView);
        LayoutInflater.from(context).inflate(R.layout.item_list_item, this, true);
        tvName = (TextView) findViewById(R.id.tvName);
        ivIcon = (ImageView) findViewById(R.id.ivIcon);
    }

    public void setItem(Item item)
    {
        tvName.setText(item.getName());
    }
}

Although I'm adding a custom style (R.style.GreenCardView) to the super constructor call at line 7, it initializes every instance of this class with the default white style. Why is this the case?

edit: style

<style name="GreenCardView" parent="CardView.Dark">
    <item name="contentPadding">@dimen/default_margin</item>
    <item name="cardBackgroundColor">@color/guiColor</item>
    <item name="cardElevation">@dimen/cardElevation</item>
    <item name="cardCornerRadius">@dimen/cardCornerRadius</item>
    <item name="android:foreground">?android:attr/selectableItemBackground</item>
</style>

Upvotes: 4

Views: 526

Answers (1)

alanv
alanv

Reputation: 24114

The third argument to the View constructor needs to be a theme attribute, e.g. R.attr.myCardViewStyle. You will need to specify the value of the attribute in your app theme and define the attribute in attrs.xml.

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...
    <attr name="myCardViewStyle" format="reference" />
</resources>

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    ...
    <style name="AppTheme" parent="...">
        ...
        <item name="myCardViewStyle">@style/GreenCardView</item>
    </style>
</resources>

Upvotes: 2

Related Questions