简体   繁体   English

我可以覆盖可绘制形状的某些属性吗?

[英]Can I override some attribute of drawable shape?

I have two buttons, they are same shape, only color is different 我有两个按钮,它们是相同的形状,只有颜色不同

b1.xml b1.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <stroke android:width="5px" android:color="#000000" />
    <solid
        android:color="#ff0000"/>
</shape>

b2.xml b2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <stroke android:width="5px" android:color="#000000" />
    <solid
        android:color="#00ff00"/>
</shape>

layout.xml layout.xml

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/b1"
    android:text="B1" />


<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/b2"
    android:text="B2" />

If I want to create 100 button with different colors, I need create 100 drawable xml. 如果我想创建100个不同颜色的按钮,我需要创建100个可绘制的xml。

Can I only create one drawable xml, and then override color or other attributes in layout xml? 我可以只创建一个可绘制的xml,然后覆盖布局xml中的颜色或其他属性吗?

Via XML no you can't. 通过XML,你不能。 XML are fixed elements if you need dynamic processing, use Java. 如果需要动态处理,XML是固定元素,使用Java。

In your specific case you can try to achieve what you need using the Drawable paint and ColorFilter, something like that: 在您的特定情况下,您可以尝试使用Drawable paint和ColorFilter来实现您所需的功能,如下所示:

Button b1 = (Button) findViewById(R.id.button1);
ShapeDrawable sd = (ShapeDrawable) b1.getBackground();
sb.getPaint().setColor(color);
sb.setColorFilter(... something);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM