Android以编程方式创建按钮边框 [英] Android programmatically create button border

查看:64
本文介绍了Android以编程方式创建按钮边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个在活动开始时通过代码创建按钮的应用程序(按钮的数量取决于数组中的值的数量).每个单独按钮的颜色由数组中的相应值定义,创建按钮时会设置按钮颜色.按钮没有文本,并且由于直接设置背景颜色,因此不是9个色块图像(按钮的颜色必须尽可能接近给定的值).

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).

我的问题是我的布局背景是黑色的,也可能有一个黑色的按钮.这意味着有时看不见某些按钮,因此我需要添加某种形式的边框.一些谷歌搜索表明,即使使用xml布局,也不容易做到这一点.

The problem that I have is that my layout background is black, 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.

到目前为止,最好的建议是在每个按钮周围绘制一个矩形(不理想,但是如果可行的话……),问题在于,我看到的绘制矩形的唯一方法是在onDraw视图中我认为我无法利用.

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.

推荐答案

我可以想到一个可能有效或可能无效的hack(我尚未对其进行测试).请尝试一下,也许会提供更清洁的解决方案-

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:对不好的代码格式表示歉意,我还没有弄清楚如何在StackOverflow上正确地做到这一点.

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

这篇关于Android以编程方式创建按钮边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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