RadioButton设置图片(位置、大小)的方法和文字颜色设置成选择器

RadioButton设置图片(位置、大小)的方法

第一种
在代码中修改。

  1. 第一步

先找到你的RadioButton控件:

RadioButton  rbtn=RadioButton)findViewById(R.id.myrbtn);
  1. 第二步

找到你的图片资源

Drawable drawable = getResources().getDrawable(R.drawable.img_rb);//找到你的图片
drawable.setBounds(0, 0, 60, 60);//给图片设置大小,4个参数分别是左上右下
rb.setCompoundDrawables(null, drawable, null, null);

第二种
自定义一个RadioButton

  1. 第一步
    在values文件夹下创建arrts.xml
    RadioButton设置图片(位置、大小)的方法和文字颜色设置成选择器_第1张图片
    并在arrts.xml里定义一个我们自己的图片属性(drawableTop)。
<resources>

    <declare-styleable name="MyRadioButton">
        <attr name="drawableTop" format="reference"/>
    declare-styleable>
resources>
  1. 第二步
    定义MyRadioButton类,继承自RadioButton
public class MyRadioButton extends RadioButton {
    private Drawable drawable;
    public MyRadioButton(Context context) {
        super(context);
    }
    @SuppressLint("UseCompatLoadingForDrawables")
    public MyRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton);//获取我们定义的属性
        drawable = typedArray.getDrawable(R.styleable.MyRadioButton_drawableTop);
        drawable.setBounds(0, 0, 80, 80)//图片大小
        this.setCompoundDrawables(null, drawable, null, null);//设置位置
    }
}
  1. 第三步
    在布局文件中使用
<com.example.bletest.myview.MyRadioButton
               android:id="@+id/btn_health"
               android:layout_width="0dp"
               android:layout_height="wrap_content"
               android:button="@null"
               attr:drawableTop="@animator/btn1_select"
               android:textColor="@drawable/select_color"
               android:text="@string/btn_1"
               android:textSize="10sp"
               android:gravity="center"
               android:layout_weight="1"/>

我感觉还是第二种方法比较好,一劳永逸。

文字颜色设置成选择器

创建:select_color.xml


<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false"   android:color="@color/grey"/>
    <item android:state_checked="true" android:color="@color/orange"/>
selector>

引用:

android:textColor="@drawable/select_color"

你可能感兴趣的:(android)