首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将属性注入到Android上的可绘制资源文件中

将属性注入到Android上的可绘制资源文件中
EN

Stack Overflow用户
提问于 2015-03-19 14:35:52
回答 1查看 365关注 0票数 0

我试图找到重用资源文件的最佳方法。在这个例子中,我试图为Android创建一个幽灵按钮。我有一个鬼按钮可绘制xml文件来定义背景,但我希望能够指定颜色(特别是,而不使用基于主题的定义颜色的)。

ghost.xml:

代码语言:javascript
复制
  <shape
  android:shape="rectangle">
  <corners android:radius="@dimen/ghost_button_corner" />
  <solid android:color="@android:color/transparent" />
  <stroke android:width="@dimen/ghost_button_stroke_size" android:color="?attr/ghost_color" /></shape>

ghost_style.xml:

代码语言:javascript
复制
<!-- STYLABLE -->
<attr name="ghost_color" format="reference" />

<!-- STYLES -->
<style name="GhostButtonBlack" parent="@style/GhostButton">
    <item name="ghost_color">@android:color/black</item>
</style>

<style name="GhostButtonWhite" parent="@style/GhostButton">
    <item name="ghost_color">@android:color/white</item>
</style>

<!-- BASE -->
<style name="GhostButton" parent="android:style/Widget.Button">
    <item name="android:textSize">@dimen/ghost_button_text_size</item>
    <item name="android:textColor">?attr/ghost_color</item>
    <item name="android:background">@drawable/ghost</item>
</style>

在layout.xml内部:

代码语言:javascript
复制
    <Button
    style="@style/GhostButtonWhite"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_margin="5dp"
    android:text="White Ghost Button" />

但我现在得到了以下例外:

代码语言:javascript
复制
Caused by: java.lang.RuntimeException: Failed to resolve attribute at index 5 
at android.content.res.TypedArray.getColorStateList(TypedArray.java:425)
at android.widget.TextView.<init>(TextView.java:987)

注意:我认识到这种类型的样式可以通过代码完成。我理想的解决方案是使用,不使用代码,只使用资源。

EN

回答 1

Stack Overflow用户

发布于 2015-03-19 14:43:32

我认为您应该从您的形状获得GradientDrawable,并应用如下不同的颜色规划:

代码语言:javascript
复制
GradientDrawable mygrad = (GradientDrawable) view.getBackground();
color = inflater.getContext().getResources().getColor(yourcolorinstyles);
mygrad.setColor(color);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29147402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档