Change drawable start color and end color dynamically in android activity class

孤人 提交于 2019-12-03 21:04:51

Yes, it is possible. You should use GradientDrawable to do this.

int colors[] = { 0xff255779, 0xffa6c0cd };

GradientDrawable gradientDrawable = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM, colors);

view.setBackgroundDrawable(gradientDrawable);

Change color code as per your requirement. Though I used Color.parseColor("color code"), its not working.

There are some option for Orientation like following.

GradientDrawable.Orientation.BOTTOM_TOP;
GradientDrawable.Orientation.LEFT_RIGHT;
GradientDrawable.Orientation.RIGHT_LEFT;

Chintan's solution is good enough if you don't mind to create the GradientDrawable again, but if you just want to change the colors without touching other attributes like padding etc, you can simply use setColors. In the following case it shows how to change startColor, centerColor, and endColor.

int color = screenshot.getPixel(x, y);
GradientDrawable drawable = (GradientDrawable)binding.layoutStation.getBackground();
int colors[] = { color, 0xffffffff, color };
drawable.setColors(colors);

new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[]{0xFF141a24, 0xFF293f49, 0xFF72554c})

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!