Android自定义方式设置drawableleft图片大小

1,values/attrs.xml 文件中:自定义rb_width 和 rb_height 两个属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyRadioButton">
        <attr name="rb_width" format="dimension"/>
        <attr name="rb_height" format="dimension"/>
    </declare-styleable>
</resources>

2,自定义RadioButton,此方法对TextView内的图标也适用(自定义TextView)

public class MyRadioButton extends AppCompatRadioButton {

    private float mImg_width;
    private float mImg_height;

    public MyRadioButton(Context context) {
        super(context);
    }

    public MyRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton);
        mImg_width = t.getDimension(R.styleable.MyRadioButton_rb_width, DisplayUtil.dp2px(25));
        mImg_height = t.getDimension(R.styleable.MyRadioButton_rb_height, DisplayUtil.dp2px(25));
        t.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //让RadioButton的图标可调大小 属性:
        Drawable drawableLeft = this.getCompoundDrawables()[0];//获得文字左侧图片
        Drawable drawableTop = this.getCompoundDrawables()[1];//获得文字顶部图片
        Drawable drawableRight = this.getCompoundDrawables()[2];//获得文字右侧图片
        Drawable drawableBottom = this.getCompoundDrawables()[3];//获得文字底部图片
        if (drawableLeft != null) {
            drawableLeft.setBounds(0, 0, (int) mImg_width, (int) mImg_height);
            this.setCompoundDrawables(drawableLeft, null, null, null);
        }
        if (drawableRight != null) {
            drawableRight.setBounds(0, 0, (int) mImg_width, (int) mImg_height);
            this.setCompoundDrawables(null, null, drawableRight, null);
        }
        if (drawableTop != null) {
            drawableTop.setBounds(0, 0, (int) mImg_width, (int) mImg_height);
            this.setCompoundDrawables(null, drawableTop, null, null);
        }
        if (drawableBottom != null) {
            drawableBottom.setBounds(0, 0, (int) mImg_width, (int) mImg_height);
            this.setCompoundDrawables(null, null, null, drawableBottom);
        }
    }

}

3,在xml文件中使用属性控制RadioButton 中的图片大小

<txkj.xian.com.txproject.widget.MyRadioButton
            android:id="@+id/rb_ali_pay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:button="@null"
            app:rb_width="20dp"
            app:rb_height="20dp"
            android:layout_centerVertical="true"
            android:drawableRight="@drawable/selector_radio"
            android:checked="false"
            android:clickable="false" />

你可能感兴趣的:(java基础相关,Android)