标签:
我们都知道xml文件里写入的RadioButton可以给它的颜色设置一个selector,很轻松实现选中与未选中即点击后字体颜色发生改变,但是代码里动态加入的radioButton应该如何设置呢
今天为大家带来一个Demo有关动态添加的RadioButoon实现字体颜色改变
main_activity.xml:代码里写入两个固定的radioButton
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<RadioGroup
android:id="@+id/rg_my"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/rd_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第1个"
android:textColor="@drawable/text_selector"/>
<RadioButton
android:id="@+id/rd_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第2个"
android:textColor="@drawable/text_selector"/>
</RadioGroup>
</LinearLayout>
mainActivity:动态循环添加RadioButton
package com.ac.myedittextdemo;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener {
private RadioGroup rg_my;
private RadioButton rd_1, rd_2, radioButton;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
rg_my = (RadioGroup) findViewById(R.id.rg_my);
rd_1 = (RadioButton) findViewById(R.id.rd_1);
rd_2 = (RadioButton) findViewById(R.id.rd_2);
for (int i = 3; i < 6; i++) {
radioButton = new RadioButton(MainActivity.this);
radioButton.setText("第" + i + "个");
radioButton.setId(i);
radioButton.setTextColor(getResources().getColorStateList(R.color.black));
rg_my.addView(radioButton);
}
rg_my.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for (int i = 0; i < group.getChildCount(); i++) {
RadioButton radioButton2 = (RadioButton) group.getChildAt(i);
radioButton2.setTextColor(getResources().getColor(R.color.black));
if (group.getCheckedRadioButtonId() == radioButton2.getId()) {
radioButton2.setTextColor(getResources().getColor(R.color.color_green_newsatient));
}
}
}
}
这里有在radioButton的选中事件里循环一遍radiogroup里radioButton并通过id判断选中状态进行设置颜色
标签:
原文地址:http://www.cnblogs.com/achen0502/p/5406960.html