Fork me on GitHub

Thursday, August 6, 2015

StateListDrawable DSL for cleaner button styles.

XML is wordy and not programmable. One of the major goal of Scaloid is to replace XMLs with Scala code, to be more concise, type-safe and programmable. Scaloid 4.0-RC2 provides a new way to build StateListDrawable without XML. For example, given the XML drawable selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item   android:state_checked="true"
            android:drawable="@drawable/drumset_on"/>
    <item   android:state_checked="false"
            android:drawable="@drawable/drumset_off"/>
</selector>

This can be written with SStateListDrawable as shown here:
new SStateListDrawable {
  +=(R.drawable.drumset_off, -SELECTED)
  +=(R.drawable.drumset_on, SELECTED)
}
It is definitely much cleaner and programmable. For example, we can write a program that returns a single-colored drawable for buttons:
def c(color: Int) = new ColorDrawable(color)

def btn(normal:Int, pressed:Int) = new SStateListDrawable {
  +=(c(pressed), PRESSED)
  +=(c(Color.LTGRAY), -ENABLED)
  +=(c(normal))
}
We pass normal color and pressed color in an Int type color code. We can further think that pressed color can be automatically determined by a normal color; It is really easy to implement:
def btn(normal:Int): SStateListDrawable = btn(normal, pressedColor(normal))
SStateListDrawable is included in Scaloid library, and the implementation of btn and pressedColor implemented in org.scaloid.util.Styles, which is included in Scaloid-util package.

The implementation is quite straightforward, take a look at the code, and you can easily have a conception about this idea:

Source of SStateListDrawable (Scaloid package)
Source of Styles (Scaloid-util package)

No comments:

Post a Comment