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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With