简体   繁体   English

修改Android代码中可绘制形状的渐变

[英]Modify the gradient of a shape drawable in code in Android

I've been scouring the web and SO but still no luck. 我一直在网上搜索,但还是没有运气。

Problem: 问题:

App connects to a server to retrieve a few colours that are then assigned to various controls in the app. 应用程序连接到服务器以检索一些颜色,然后将这些颜色分配给应用程序中的各种控件。

My problem is that I'd like to use style defined in xml for Edittext and Button controls, but if i set the background colour of the control it removes any of my predefined styling. 我的问题是我想将xml中定义的样式用于Edittext和Button控件,但是如果我设置控件的背景色,它将删除我的任何预定义样式。

I have a selector drawable with defined styles for pressed, focused and normal 我有一个可绘制的选择器,它具有用于按下,聚焦和正常的已定义样式

How can I modify the gradient within the selector from code. 如何从代码中修改选择器中的渐变。

Please note: it is a requirement that the colour comes from the server, (which is just a hex value) 请注意:这是颜色必须来自服务器的要求(这只是一个十六进制值)

main (JAVA) 主(JAVA)

int gradientColour1= "comes from server"
int gradientColour2= "also comes from server"

Button btnNext = (Button)findViewById(R.id.btnnext);
btnNext.setBackgroundColor(gradientColor1);

is there a way I can do something like this: (pseudo) 有没有办法我可以做这样的事情:(伪)

Gradient grad = new Gradient(gradientColor1,gradientColor2,90);
btnNext.setBackgroundGradient(grad);
btnNext.setBorderRadius(15);

I need to be able to get the colours via a webrequest, not predefined in xml 我需要能够通过webrequest获取颜色,而不是在xml中预定义

There must be a way that I can do this. 我一定有办法做到这一点。 If I have to do away with the pre-defined styles then that's fine. 如果我必须取消预定义的样式,那很好。

I'm pretty new to android/java and Stack Overflow so please be gentle Thanks in advance 我是android / java和Stack Overflow的新手,所以请保持谨慎

Try something like this... 试试这样的东西...

public void setGradientColor(int endColor, int startColor) {
    GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]  {endColor, startColor});
    gradient.setShape(GradientDrawable.RECTANGLE);
    gradient.setCornerRadius(10.f);
    btnNext.setBackgroundDrawable(gradient);
}

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

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