Android的编程方式创建按钮边框边框、按钮、方式、Android

2023-09-07 12:09:02 作者:小孩子才问你为什么不理我了,成年人都是默契地相互疏远。今天小

我创建通过创建code按钮选择一个活动开始时,一个应用程序(按钮的数量取决于值的数量在一个数组)。每个单独的按钮的颜色是由一个相应的值在一个数组中定义,当我创建按钮的按钮颜色设定。按钮没有文本,并且由于直接设置背景颜色,并不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.

任何想法?

推荐答案

我能想到一个黑客可能会或可能无法正常工作(我还没有测试出来)的。请摆弄它,也许配有一个清洁的解决方案 -

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:很抱歉没能坏code格式,我还没有完全想通了如何做正确的计算器

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