views:

67

answers:

2

When using the "selector" to specify different images for buttons for different states, such as pressed, focused etc, do I have to write an xml file for each button? I have about 15-20 buttons in my app, so was wondering if there is a way to write just one xml and refer to parts of it?

Thanks Chris

A: 

There is no way to refer to parts of a StateListDrawable, at least that I am aware of.

However, since StateListDrawables are usually used for button backgrounds, it is unclear why you need more than one in the first place.

CommonsWare
So for eg, I have a load button and a save button. I want to show btn_load.png by default, and btn_load_click.png on pressed or focused. Similarly, I want to show btn_save.png by default and btn_save_click.png on pressed or focused. Do I need to create load.xml and save.xml separately and have them specified in loadButton and saveButton?
Chris
A: 

StateListDrawable changes the Drawable based on the current state, as state changes at runtime. Choosing what Drawable to use initially is something you already do when specifying the Drawable in the first place.

Even classes like LevelListDrawable still require you to specify the level to the Drawable, not on the actual View the Drawable is used on and AFAIK Android automatically checks if a Drawable can handle states and if so passes them. The Drawable never gets reference to the View the Drawable is being used on.

I would just create multiple Drawable files for each button. If you want to share certain attributes of the Button like text color, padding, font sizing, etc you should use Android styles.

Android styles would let you have styles like BlueButton, RedButton, GreenButton which you can inherit styles. So you could have BlueButton that sets the text color, text size, text shadows, the drawable for blue etc, then create another style for Red that just inherits BlueButton and only changes the Drawable (although it can change any attribute it wishes) and then just use them on your Button widgets. You would still need to have multiple Drawable files for the styles to link to, but the styles can all be in one file.

William