Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the resource id for the drawable reference used in styled attribute

Having this custom view MyView I define some custom attributes:

<?xml version="1.0" encoding="utf-8"?> <resources>     <declare-styleable name="MyView">         <attr name="normalColor" format="color"/>         <attr name="backgroundBase" format="integer"/>     </declare-styleable>    </resources> 

And assign them as follows in the layout XML:

    <com.example.test.MyView         android:id="@+id/view1"         android:text="@string/app_name"         . . .         app:backgroundBase="@drawable/logo1"         app:normalColor="@color/blue"/> 

At first I thought I can retrieve the custom attribute backgroundBase using:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0); int base = a.getInteger(R.styleable.MyView_backgroundBase, R.drawable.blank); 

Which works only when the attribute is not assigned and the default R.drawable.blank is returned.
When app:backgroundBase is assigned an exception is thrown "Cannot convert to integer type=0xn" because, even though the custom attribute format declares it as integer, it really references a Drawable and should be retrieved as follows:

Drawable base = a.getDrawable(R.styleable.MyView_backgroundBase); if( base == null ) base = BitMapFactory.decodeResource(getResources(), R.drawable.blank); 

And this works.
Now my question:
I really don't want to get the Drawable from the TypedArray, I want the integer id corresponding to app:backgroundBase (in the example above it would be R.drawable.logo1). How can I get it?

like image 335
ilomambo Avatar asked May 04 '13 13:05

ilomambo


People also ask

What are drawable resources?

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon . There are several different types of drawables: Bitmap File.

How do I get to the drawable folder on Android?

In Android Studio inside the res folder, one can find the drawable folder, layout folder, mipmap folder, values folder, etc. Among them, the drawable folder contains the different types of images used for the development of the application.

How do I make my Android drawable?

There are two ways to define and instantiate a Drawable besides using the class constructors: Inflate an image resource (a bitmap file) saved in your project. Inflate an XML resource that defines the drawable properties.


1 Answers

It turns out that the answer was right there:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, defStyle, 0); int base = a.getResourceId(R.styleable.MyView_backgroundBase, R.drawable.blank); 
like image 169
ilomambo Avatar answered Sep 28 '22 07:09

ilomambo