【问题标题】:Injecting attributes into drawable resources files on Android在 Android 上将属性注入到可绘制资源文件中
【发布时间】:2015-03-19 14:35:52
【问题描述】:

我正在努力寻找重用资源文件的最佳方式。在此示例中,我尝试为 Android 创建一个幽灵按钮。我有一个定义背景的幽灵按钮可绘制 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>

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

注意 我认识到这种类型的样式可以通过代码完成。我理想的解决方案将涉及 no 代码;只是资源。

【问题讨论】:

    标签: android android-layout attributes android-drawable


    【解决方案1】:

    我认为你应该从你的形状中获取 GradientDrawable 并像这样以编程方式应用不同的颜色:

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

    【讨论】:

    • 也许您可以尝试将其作为具有不同状态的选择器
    • 你做了一个 ghostbutton.xml schemas.android.com/apk/res/android">
    • 不确定如何解决问题?如何通过资源/样式设置“blackbutton”/state_checked“false”?
    • 抱歉耽搁了。如果您使用复选框而不是按钮,它会自动从未选中状态更改为选中状态。但我不确定是否可以使用多个状态。
    • 我想创建任意数量的 GhostButtonColor 样式,方法是简单地定义“ghost_color”属性并将其传递到使用该属性的 ghost drawable 中。这是我正在进行的一个相当大的造型设计中的一小步。我正在寻找一个非黑客解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多