Android常用控件之RadioGroup

目录:android.widget.RadioGroup

xml布局中:(包含按钮选中状态及文本选中状态的改变)



    

        

        
    

按钮背景选择器:selector_rb_bg.xml



    
    

round_grey_press.xml



    
    
    
    

round_grey_default.xml



    
    
    
    

res color:

#66666666
#b3cccccc

按钮字体颜色选择器:selector_rb_color_bg.xml



    
    

代码使用:
public class MainActivity extends AppCompatActivity {

    private RadioGroup rg_radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        rg_radioGroup = (RadioGroup) findViewById(R.id.rg_radioGroup);
        //设置按钮组监听
        rg_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //选中位置 checkedId
            }
        });

        //通过代码手动设置选中按钮
        //RadioButton childAt = (RadioButton) rg_radioGroup.getChildAt(0);
        //childAt.setChecked(true);
    }

}

补充:通过代码编写RadioButton并设置相应效果:

/**新建单选按钮*/
private RadioButton getRadioButton(RadioGroup.LayoutParams rbParams, String rbTitle){
    final RadioButton rb = new RadioButton(context);
    rb.setText(rbTitle);
    rb.setTextAppearance(context, R.style.common_text_gray_style);//代码添加style
    rb.setTextColor(getResources().getColor(R.color.tab_default_bg));//注意被上面style字体颜色属性覆盖
    rb.setLayoutParams(rbParams);//width=60dp
    rb.setButtonDrawable(getResources().getDrawable(android.R.color.transparent));//android:button="@null"
    rb.setPadding(0, DensityUtils.dp2px(context, 5), 0, DensityUtils.dp2px(context, 5));
    rb.setBackgroundResource(R.drawable.selector_buy_rb_bg);
    rb.setGravity(Gravity.CENTER);
    rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //android:textColor="@drawable/selector_buy_rb_tv_color"
            if (isChecked)
                rb.setTextColor(getResources().getColor(R.color.white));
            else
                rb.setTextColor(getResources().getColor(R.color.tab_default_bg));
        }
    });
    return rb;
}

你可能感兴趣的:(Android常用控件之RadioGroup)