android动态切换图片,android radioButton动态切换图片

1、属性设置

在res/values/attrs.xml定义属性文件

2、LayOut xml配置文件

xmlns:attRadoi="http://schemas.android.com/apk/res/com.my.test.pro"

定义属性的命令空间,com.my.test.pro为工程的包定义

定义自定义的属性如下:

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"

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值