我可以覆盖可绘制形状的某些属性吗? [英] Can I override some attribute of drawable shape?

查看:76
本文介绍了我可以覆盖可绘制形状的某些属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个按钮,它们的形状相同,只是颜色不同

I have two buttons, they are same shape, only color is different

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

<?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" />

如果要创建100个具有不同颜色的按钮,则需要创建100个可绘制的xml.

If I want to create 100 button with different colors, I need create 100 drawable xml.

我只能创建一个可绘制的xml,然后覆盖布局xml中的颜色或其他属性吗?

Can I only create one drawable xml, and then override color or other attributes in layout xml?

推荐答案

通过XML不能,您不能.如果需要动态处理,XML是固定元素,请使用Java.

Via XML no you can't. XML are fixed elements if you need dynamic processing, use Java.

在您的特定情况下,您可以尝试使用Drawable绘画和ColorFilter来实现所需的功能,

In your specific case you can try to achieve what you need using the Drawable paint and ColorFilter, something like that:

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

这篇关于我可以覆盖可绘制形状的某些属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆