14

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.

James Veenstra
  • 193
  • 1
  • 6
  • 2
    Still searching on this - found this note http://groups.google.com/group/android-developers/browse_thread/thread/140ea9d8992434d7/28d94f078f15a6b4?lnk=gst&q=drawable#28d94f078f15a6b4 which I read as saying it's not possible. – James Veenstra May 05 '10 at 03:22
  • I found another discussion thread (lost the URL) where it was said that allowing arbitrary drawable classes in XML markup was disallowed due to security considerations. Which makes sense: It would be relatively easy to supply a "malicious Drawable" for a harmless application, and the drawable's code would be executed in the context of the innocent app. – class stacker Feb 27 '13 at 13:37

2 Answers2

3

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.

Community
  • 1
  • 1
joseph
  • 1,165
  • 1
  • 7
  • 16
-4

For custom view classes in a resource xml checkout this example:

http://developer.android.com/guide/topics/ui/custom-components.html#modifying

Not sure if that applies to classes that extend Drawable, but its worth a try... One other thing, I kept missing this note toward the bottom for classes defined in their own class file:

If your custom View component is not defined as an inner class, then you can, alternatively, declare the View component with the XML element name, and exclude the class attribute. For example:

<com.android.notepad.MyEditText
 id="@+id/note"
 ... />
Churlbong
  • 148
  • 6