4

I am trying to create a custom component which inherits from RelativeLayout.

In my xml layout file, I have:

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

My question is how can I create a Drawable class in the constructor of Mycomponent?

I have tried to read the source code of ImageView, but it seems tried to some android Internal.R .

Is there anyway I can do that in my code.

Thank you.

Aleks G
  • 54,795
  • 26
  • 160
  • 252
michael
  • 99,904
  • 114
  • 238
  • 340

2 Answers2

16

I think Luksprog it's wrong, I have an easy solution to access you custom component "src" data without styleable, just calling the AttributeSet:

attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0);

Here you can see my example to make bitmaps size more cheap, jeje.

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

Now you will have something in the xml like this:

<com.example.com.jfcogato.mycomponent.CustomView
    android:id="@+id/tAImageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:src="@drawable/big_image_example"/>
jfcogato
  • 3,211
  • 3
  • 18
  • 19
  • 1
    `this.setImageDrawable(getResources().getDrawable(src_resource))` ... should be used to support drawables of all types. Your code only supports images. – Brad Johnson Jan 17 '15 at 19:53
1

I've also seen suggestions that you can do this...

    int attributeIds[] = { android.R.attr.src };
    TypedArray a = context.obtainStyledAttributes(attributeIds);
    int resourceId = a.getResourceId(0, 0);
    a.recycle();

In my experience this code compiles but returns 0 at runtime.

So yeah... go with jfcogato's answer above.

SharkAlley
  • 11,021
  • 5
  • 50
  • 42