Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference a drawable class in Android XML

Tags:

android

I've created a class that extends drawable that I'd like to reference inside a resource xml. I happen to need it in a selector, like so:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_pressed="false" 
android:drawable="com.sample.android.contacts.TopBarCollapsed"
/>
<item android:state_window_focused="true" android:state_pressed="true" android:drawable="@drawable/top_switcher_collapsed_selected" />
<item android:state_focused="true" android:drawable="@drawable/top_switcher_collapsed_focused" />

com.sample.android.contacts.TopBarCollapsed is the class that extends drawable.

like image 271
James Veenstra Avatar asked Apr 30 '10 18:04

James Veenstra


People also ask

How do you reference drawable Android?

In your Android/Java source code you can also refer to that same image like this: Resources res = getResources(); Drawable drawable = res. getDrawable(R.

How do I get URI from drawable?

You should use ContentResolver to open resource URIs: Uri uri = Uri. parse("android. resource://your.package.here/drawable/image_name"); InputStream stream = getContentResolver().

What is drawable XML file?

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.


1 Answers

I believe this was answered well here: https://stackoverflow.com/a/11024035/2662474

Unfortunately it is not possible to use custom drawables in XML files due to potential security issues. See here for a Google Groups thread about this very topic with a response from Romain Guy, one of the Android developers.

You can still use them in your Java code though.

In that link Roman writes:

Custom drawables are not allowed from XML, mostly for security reasons. XML drawables can be loaded as resources by other processes (including Launcher or the system process) and it would be a terrible idea to run random 3rd party code in these processes.

Security is essential, but certainly it would be nice if there was a clean way to have more consistency and control as a developer.

like image 165
joseph Avatar answered Oct 14 '22 09:10

joseph