3

In my app I want all buttons to have the same background.

For API 21 and newer ?android:attr/selectableItemBackgroundBorderless

For older APIs ?android:attr/selectableItemBackground

How do I set button's background in XML so that it references correct drawable based on android version?

Egis
  • 5,081
  • 5
  • 39
  • 61

2 Answers2

4

Inside styles.xml in res/values folder create a theme for application:

<style name="AppTheme" parent="AppTheme">
    <item name="android:buttonStyle">?android:attr/selectableItemBackground</item>
</style>

Inside styles.xml in res/values-v21 folder create a theme for application:

<style name="AppTheme" parent="AppTheme">
    <item name="android:buttonStyle">?android:attr/selectableItemBackgroundBorderless</item>
</style>

Apply a theme to application in AndroidManifest.xml:

(...)
<application
    android:theme="@style/AppTheme">
(...)
R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
  • Thanks. This solution works but I wonder if it's possible to do the same thing without using styles. A better solution for me would be if I could somehow wrap android drawables into my own drawables, put them in drawable, drawable-v21 folders and then just set background directly on the view? – Egis Oct 18 '16 at 13:26
  • Declare drawables with the same name in `res/drawable` and `res/drawable-v21` and point `android:background` of Button to that drawable? I am not really sure if that is what you mean. – R. Zagórski Oct 18 '16 at 14:33
  • Yes, but I want my drawable to use `?android:attr/selectableItemBackground`. How do I do that? What type of drawable do I need? Is it even possible? – Egis Oct 18 '16 at 15:50
0

Create two style. Reference: Creating styles-v21.xml

After first step: Set ButtonStyle Reference: https://stackoverflow.com/a/14033420/7001152

Community
  • 1
  • 1
Barış Söbe
  • 470
  • 4
  • 7