RadioButton之drawableTop及drawablePadding属性详解 | 您所在的位置:网站首页 › 设置drawable大小 › RadioButton之drawableTop及drawablePadding属性详解 |
现在正在做的一个项目,项目里面底部是一个Tab,如下图:
选中某个button后该button上的图片点亮,因为涉及到了checked属性,所以我采用了RadioGroup来做这个Tab。大家都知道,RadioButton里面有一个drawableTop属性,正好可以满足这个项目的需求,但是在xml文件里面,却没有控制上方图片大小的属性,这个让人很伤脑筋,怎么控制drawableTop图片的大小呢?我们要从源码入手: 首先我们来了解一下dp转换为px的方法,因为在java代码中设置图片大小所用的单位肯定是px,有悖于适配原则,所以我们设置一个单位为dp的数,将该数转换成px,间接设置图片的大小,这种做法可以满足不同分辨率下图片的显示: int scale = context.getResources().getDisplayMetrics().density;// 屏幕密度 px = (int)(dp*scale+0.5f); 进入正题,设置drawableTop图片大小。首先从资源文件中选一张图片drawable,设置该图片的大小: Drawable top = getResources().getDrawable(R.drawable.home_1); top.setBounds(0, 0, (int) (25 * scale + 0.5f), (int) (25 * scale + 0.5f)); 设置大小时所用的25是dp,根据实际情况可以取不同的值。图片大小调整完毕。 接着通过RadioButton的setCompoundDrawables()方法将图片放到button上: ((RadioButton) findViewById(R.id.rb_home)).setCompoundDrawables(null, top, null, null); 该方法的四个参数分别是左、上、右、下四个drawable,我们这里只用到drawableTop,所以其他三个地方填null即可。 ok,自定义大小的图片就这样放到了RadioButton上。到此我们的目标已经完成了,但是每次都在代码中动态设置很麻烦,所以我们可以给RadioButton自定义两个属性:drawableTopHeight,drawableTopWidth来方便我们的使用,关于自定义属性具体的流程和含义就不多讲了,直接上代码: values下的attrs.xml: MyRadioButton.java: import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.RadioButton; public class MyRadioButton extends RadioButton { private Drawable drawableTop; private int mTopWith, mTopHeight; public RadioButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context, attrs); } public MyRadioButton(Context context, AttributeSet attrs) { super(context, attrs); initView(context, attrs); } public MyRadioButton(Context context) { super(context); initView(context, null); } private void initView(Context context, AttributeSet attrs) { if (attrs != null) { float scale = context.getResources().getDisplayMetrics().density; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyRadioButton); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.MyRadioButton_drawableTop: drawableTop = a.getDrawable(attr); break; case R.styleable.MyRadioButton_drawableTopWith: mTopWith = (int) (a.getDimension(attr, 20) * scale + 0.5f); break; case R.styleable.MyRadioButton_drawableTopHeight: mTopHeight = (int) (a.getDimension(attr, 20) * scale + 0.5f); break; } } a.recycle(); setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null); } } // 设置Drawable定义的大小 @Override public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom) { if (top != null) { top.setBounds(0, 0, mTopWith |
CopyRight 2018-2019 实验室设备网 版权所有 |