最近做项目用的是RadioGroup+Fragment进行来回切换,这样方便也很多,但是也出现问题,drabTop的图片不能改变大小,所以写此博客记录一下
效果图
/** * Created by Sinocall on 2015-10-21. */ public class MyRadioButton extends RadioButton{ //图片大小 //private int drawableSize; public MyRadioButton(Context context) { this(context,null); } public MyRadioButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MyRadioButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton); //drawableSize = a.getDimensionPixelSize(R.styleable.MyRadioButton_rbDrawableTopSize, 50); Drawable drawableTop = a.getDrawable(R.styleable.MyRadioButton_rbDrawableTop); //释放资源 a.recycle(); setCompoundDrawablesWithIntrinsicBounds(null,drawableTop,null,null); } @Override public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom) { super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); if(top != null){
//这里只要改后面两个参数就好了,一个宽一个是高,如果想知道为什么可以查找源码 top.setBounds(0,0,70,60); } setCompoundDrawables(left,top,right,bottom); } }
在values下新建一个attrs.xml然后把下面代码复制进去就好
<declare-styleable name="MyRadioButton"> <attr name="rbDrawableTopSize" format="dimension"/> <attr name="rbDrawableTop" format="reference"/> </declare-styleable>在布局文件中直接使用,注意声明命名空间。就这么简单任性即可解决,本人也是在网上搜集之后改的!