简体   繁体   English

Android如何以编程方式更改单选按钮图像

[英]Android how to change the radio button image programatically

I have a radio button which I want to change the little selected icon based on a state, however its a simple on, off state. 我有一个单选按钮,我想根据状态更改选择很少的图标,但是它是简单的开,关状态。 Basically I want to make it look like an LED, I have a red image and a green image and when it is checked I want it to be green and when it is not checked I want it to be red. 基本上,我想使其看起来像一个LED,我有一个红色图像和一个绿色图像,当选中它时,我希望它是绿色,而当不选中它时,我希望它是红色。

绿色红色

Currently the options I have tried, just stick the image in the background of the whole view, and not just the small circle area. 目前,我尝试过的选项只是将图像粘贴在整个视图的背景中,而不仅仅是小圆圈区域。 like so 像这样

在此处输入图片说明

I have my two drawables generated from http://android-holo-colors.com/ 我有两个从http://android-holo-colors.com/生成的可绘制对象

radio_red.png and radio_green.png radio_red.png和radio_green.png

You have to set your radiobutton's background from Java code: 您必须通过Java代码设置单选按钮的背景:

radioButton.setButtonDrawable(R.drawable.custom_radiogroup_divider);

It works with checkbox too ;) 它也可以使用复选框;)

Create a state list drawable (see this page ) and use the android:button attribute on your RadioButton . 创建一个可绘制的状态列表(请参见本页 ),并在RadioButton上使用android:button属性。 If you want to really make sure you cover all the states, you can find the source used for Android's default radio button indicator and just swap out the drawable names. 如果您确实想确保涵盖所有状态,则可以找到用于Android默认单选按钮指示器的源代码,而只需换出可绘制名称即可。 You can find that file somewhere in your [android-sdk-directory]/platforms/android-#/data/res/drawable folder. 您可以在[android-sdk-directory]/platforms/android-#/data/res/drawable文件夹中的某个位置找到该文件。

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

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