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

将属性注入Android上的可绘制资源文件,android,android-layout,attributes,android-drawable,Android,Android Layout,Attributes,Android Drawable,我正试图找到重用资源文件的最佳方法。在这个例子中,我试图为Android创建一个ghost按钮。我有一个定义背景的ghost按钮可绘制xml文件,但我希望能够指定颜色(特别是,而不使用基于主题的定义颜色) ghost.xml: <shape android:shape="rectangle"> <corners android:radius="@dimen/ghost_button_corner" /> <solid android:color="@

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

ghost.xml:

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

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

@android:彩色/黑色
@android:彩色/白色
@尺寸/重影按钮文字尺寸
?属性/幻影颜色
@可牵引/重影
在layout.xml中:

    <Button
    style="@style/GhostButtonWhite"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_margin="5dp"
    android:text="White Ghost Button" />

但我目前遇到以下例外情况:

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)
原因:java.lang.RuntimeException:未能解析索引5处的属性
位于android.content.res.TypedArray.getColorStateList(TypedArray.java:425)
在android.widget.TextView。(TextView.java:987)
注意
我认识到这种类型的样式可以通过代码来完成。我的理想解决方案包括代码;只有资源。

我认为您应该从您的形状中获得渐变绘制,并应用不同的颜色程序。我如下所示:

GradientDrawable mygrad = (GradientDrawable) view.getBackground();
color = inflater.getContext().getResources().getColor(yourcolorinstyles);
mygrad.setColor(color);

也许您可以尝试使用不同状态的选择器来执行此操作。您可以创建一个ghostbutton.xml,但不确定这是如何解决问题的?如何通过资源/样式设置“blackbutton”/“state_checked”false?请为延迟提供sry。如果使用复选框而不是按钮,它会自动从未选中状态更改为选中状态。但是我不确定是否可以使用多个状态。我想创建任意数量的GhostButtonColor样式,只需定义“ghost_color”属性并将其传递到使用该属性的ghost drawable中即可。这是我正在进行的一个相当大的造型设计中的一小步。我正在寻找一个非黑客解决方案。