Set style programmatically doesn't work

This is the complex view code 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 add a custom style (R.style.GreenCardView) to the super-constructor call on line 7, it initializes every instance of that class with the default white style. Why is this so?

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>

      

+3


source to share


1 answer


The third argument to the View constructor should be a theme attribute, eg. R.attr.myCardViewStyle

... You will need to specify the value of the attribute in the application 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>

      

+1


source







All Articles