以编程方式设置样式不起作用

时间:2014-11-25 16:56:08

标签: android android-layout

这是我写的复合视图的代码。它使用android.support.v7.widget.CardView作为父类:

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());
    }
}

虽然我在第7行的超级构造函数调用中添加了自定义样式(R.style.GreenCardView),但它使用默认的白色样式初始化此类的每个实例。为什么会这样?

编辑: 风格

<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>

1 个答案:

答案 0 :(得分:1)

View构造函数的第三个参数需要是一个主题属性,例如R.attr.myCardViewStyle。您需要在应用主题中指定属性的值,并在attrs.xml中定义属性。

RES /值/ attrs.xml:

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

RES /值/的themes.xml

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