Android:使用预定义的Drawable可编程更改按钮颜色

3

我有:

public Button[] getButtons(int buttonCount, List<String> buttonHeaders, Context activity) {
    Button[] result = new Button[buttonCount];

    for (int i = 0; i < buttonCount; i++) {

        result[i] = new Button(activity);

        result[i].setId(i);
        result[i].setText(buttonHeaders.get(i));
        result[i].setBackgroundResource(R.drawable.buttons_shape);
        result[i].setBackgroundColor(randomColor(activity));
        result[i].setTextColor(activity.getResources().getColor(R.color.white));
        result[i].setWidth(360);
        result[i].setHeight(100);
    }
    return result;
}

但是在我的可绘制文件中是这样的:
 <solid android:color="@color/white"/> 
    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>

但我想定义程序的颜色,因为颜色是随机的,当我更改背景时会返回到默认设计(PS. 抱歉我的英语 :P)

但是我希望能够指定程序的颜色,因为这些颜色是随机的。当我更改背景后,程序会回到默认设计(注:抱歉我的英语 :P)。
1个回答

0

你不能同时做两件事情... 你要么使用 view.setBackgroundDrawable(drawable); 或者使用 view.setBackGroundColor(color);


当我使用setBackgroundDrawable(drawable)设置自己的样式时,是可以的。但是当我想要使用setBackgroundColor更改颜色时,它会返回默认样式,并且只设置颜色而没有圆角。 - Maury
这是因为样式属于drawable而不是您的视图。因此,调用setBackGroundColor会删除backgroundDrawable。 - Abhishek Shukla
那么如何解决这个问题? - Maury
你可以做的一件事是,准备两个相同风格但不同颜色的drawable,并调用view.setBackgroundDrawable(drawable);而不是调用view.setBackgroundColor(color); - Abhishek Shukla
1
还有呢?因为我有大约20种不同的颜色 :/ - Maury
那么,您可能需要开发一个智能算法,它可以将透明位图(或您选择的其他格式)输入到画布中,并动态地添加彩色层,然后将其设置为视图的可绘制对象。 - Abhishek Shukla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接