我想创建一个自定义组件,继承 RelativeLayout。
在我的 xml 布局文件中是这样设置的:
<Mycomponent
android:src="@drawable/my_test_image">
<TestView>
</Mycomponent>
如何在 Mycomponent 的 constructor 里创建一个 Drawable 类?
我想查看 ImageView 的源代码,但是似乎是 android 的内部代码。
在我的代码中如何实现呢?
你要定义过一个自己的属性(例:img),再用下面的方法得到
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ButtonPreference, defStyle, 0);
//button的名称
Drawable drawable = a.getDrawable(R.styleable.MyComponent_img);
a.recycle();
public CustomView(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));
}