我试图找到重用资源文件的最佳方法。在这个例子中,我试图为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)注意:我认识到这种类型的样式可以通过代码完成。我理想的解决方案是使用,不使用代码,只使用资源。
发布于 2015-03-19 14:43:32
我认为您应该从您的形状获得GradientDrawable,并应用如下不同的颜色规划:
GradientDrawable mygrad = (GradientDrawable) view.getBackground();
color = inflater.getContext().getResources().getColor(yourcolorinstyles);
mygrad.setColor(color);https://stackoverflow.com/questions/29147402
复制相似问题