Skip to content Skip to sidebar Skip to footer

Dynamically Defining And Using Selectors

I have a ListView which has custom elements inside of it. I want to create selectors for each of those elements. Selectors themselves will not be very complicated because they need

Solution 1:

StateListDrawable states = newStateListDrawable();
int yourBackgroundColor = Color.parseColor("#FFFFFF");
// Add specific color when your view has state 'pressed'
states.addState(newint[] {android.R.attr.state_pressed}, newColorDrawable(yourBackgroundColor));
// Add other states wanted and associated drawable// ...// As StateListDrawable extend Drawable, you can use it as background for exemple       
yourView.setBackground(states);

You can add states as many as you want into your StateListDrawable (List of states available: http://developer.android.com/guide/topics/resources/color-list-resource.html). For each states combination you can set specific and dynamic drawable.

You can specify multiple states to match for a drawable

states.addState(newint[] { -android.R.attr.state_focused,
                            android.R.attr.state_selected,
                            -android.R.attr.state_pressed}, ColorDrawable(yourBackgroundColor));

This time the color will be applied if your view is not focused, is selected and is not pressed.

Solution 2:

StateListDrawable states = newStateListDrawable();
int yourBackgroundColor = Color.parseColor("#FFFFFF");
// Add specific color when your view has state 'pressed'
states.addState(newint[] {android.R.attr.state_pressed}, 
        newColorDrawable(yourBackgroundColor));
// Add other states wanted and associated drawable// ...// As StateListDrawable extend Drawable, you can use it as background for exemple       
yourView.setBackground(states);

Post a Comment for "Dynamically Defining And Using Selectors"