我們都知道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判斷選中狀態進行設置顏色