1、属性设置
在res/values/attrs.xml定义属性文件
<resources>
<declare-styleable name="ImageRadioButton">
<attr name="drawableSize" format="dimension"/>
<attr name="drawableTop" format="reference"/>
</declare-styleable>
</resources>
2、LayOut xml配置文件
xmlns:attRadoi="http://schemas.android.com/apk/res/com.my.test.pro"
定义属性的命令空间,com.my.test.pro为工程的包定义
定义自定义的属性如下:
<com.my.test.pro.view.ImageRadioButton
android:id="@+id/mytab_bt_test"
style="@style/mytabground"
android:text="TEST"
attRadoi:drawableSize="28dp"
attRadoi:drawableTop="@drawable/main_selector_test"
android:drawableTop="@drawable/main_selector_test"
</com.my.test.pro.view.ImageRadioButton>
3、源码示例
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RadioButton;
public class ImageRadioButton extends RadioButton {
private int mDrawableSize;// xml文件中设置的大小
public ImageRadioButton(Context context) {
this(context, null, 0);
}
public ImageRadioButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ImageRadioButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//Auto-generated constructor stub
Drawable drawableLeft = null, drawableTop = null, drawableRight = null, drawableBottom = null;
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ImageRadioButton);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
Log.i("ImageRadioButton", "attr:" + attr);
switch (attr) {
case R.styleable.ImageRadioButton_drawableSize:
mDrawableSize = a.getDimensionPixelSize(R.styleable.ImageRadioButton_drawableSize, 50);
Log.i("ImageRadioButton", "mDrawableSize:" + mDrawableSize);
break;
case R.styleable.ImageRadioButton_drawableTop:
drawableTop = a.getDrawable(attr);
break;
case R.styleable.ImageRadioButton_drawableBottom:
drawableRight = a.getDrawable(attr);
break;
case R.styleable.ImageRadioButton_drawableRight:
drawableBottom = a.getDrawable(attr);
break;
case R.styleable.ImageRadioButton_drawableLeft:
drawableLeft = a.getDrawable(attr);
break;
default :
break;
}
}
a.recycle();
setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawableRight, drawableBottom);
}
public void setCompoundDrawablesWithIntrinsicBounds(Drawable left,
Drawable top, Drawable right, Drawable bottom) {
if (left != null) {
left.setBounds(0, 0, mDrawableSize, mDrawableSize);
}
if (right != null) {
right.setBounds(0, 0, mDrawableSize, mDrawableSize);
}
if (top != null) {
top.setBounds(0, 0, mDrawableSize, mDrawableSize);
}
if (bottom != null) {
bottom.setBounds(0, 0, mDrawableSize, mDrawableSize);
}
setCompoundDrawables(left, top, right, bottom);
}
}