android自定义控件(7)-获取自定义ImageView的src属性

 

创建一个自定义组件,继承 ImageView。
在我的 xml 布局文件中是这样设置的:

<Mycomponent 
    android:src="@drawable/my_test_image">
</Mycomponent> 

如何在 Mycomponent 的 constructor 里创建一个 Bitmap类?

首先想查看 ImageView 的源代码,但是 它是Android的内部代码,我们无法这样使用。

  TypedArray a = context.obtainStyledAttributes(attrs,
                com.android.internal.R.styleable.ImageView, defStyle, 0);
  Drawable d = a.getDrawable(com.android.internal.R.styleable.ImageView_src);

后来发现有2种解决方案。

 

1:定义过一个自己的属性(例:img),再用下面的方法得到

 

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ButtonPreference, defStyle, 0); 
Drawable drawable = a.getDrawable(R.styleable.MyComponent_img); //button的名称
a.recycle();

 

2:通过默认属性获得:

public Mycomponent (Context context, AttributeSet attrs) {
 super(context, attrs);
 int src_resource = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0);
 this.setImageBitmap(getDrawable(getResources(),src_resource));
}

public static Bitmap getDrawable(Resources res, int id){
    return BitmapFactory.decodeStream(res.openRawResource(id));
} 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值