开发者

Android programmatically create button border

开发者 https://www.devze.com 2023-03-15 04:31 出处:网络
I\'m creating an app that creates buttons through code when an activity starts (the number of buttons depends on the number of values in an array). The colour of each individual button is defined by a

I'm creating an app that creates buttons through code when an activity starts (the number of buttons depends on the number of values in an array). The colour of each individual button is defined by a corresponding value in an array, the button colour is set when I create the button. Buttons have no text and, due to setting the background colour directly, are not 9 patch images (the colour of the button has to be as close as possible to the value given).

The problem that I have is that my layout background is b开发者_JAVA技巧lack, it's also possible to have a black button. This means that sometimes some buttons are impossible to see so I need to add some form of a border. Some googling suggests that this is not easy to do even with the xml layout.

The best suggestion so far has been to draw a rectangle around each button (not ideal but if it works...), the issue with this is that the only way that I can see to draw rectangles is in a views onDraw which I don't think that I can utilise.


I can think of a hack that might or might not work (I haven't tested it out). Please play around with it and maybe come with a cleaner solution -

button.setBackgroundColor(whatever);    
Drawable backgroundRes = button.getBackground();    
Drawable drawableRes = loadDrawable(R.drawable.white_outline);
Drawable[] drawableLayers = { backgroundRes, drawableRes };
LayerDrawable ld = new LayerDrawable(drawableLayers);
button.setBackgroundDrawable(ld);

PS: Apologies for the bad code formatting, I haven't quite figured out how to do it properly on StackOverflow.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号