我有一个ListView,里面有自定义元素。我想为每个元素创建选择器。选择器本身不会非常复杂,因为它们只需处理背景颜色而物品是悬停/选择/等。然而,这些选择器的颜色必须来自外部源,我需要能够从变量设置它们,所以一些简单的静态代码不会这样做。
答案 0 :(得分:12)
StateListDrawable states = new StateListDrawable();
int yourBackgroundColor = Color.parseColor("#FFFFFF");
// Add specific color when your view has state 'pressed'
states.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(yourBackgroundColor));
// Add other states wanted and associated drawable
// ...
// As StateListDrawable extend Drawable, you can use it as background for exemple
yourView.setBackground(states);
您可以在StateListDrawable中添加任意数量的状态(可用状态列表:http://developer.android.com/guide/topics/resources/color-list-resource.html)。 对于每种状态组合,您可以设置特定和动态可绘制。
您可以指定多个状态以匹配可绘制的
states.addState(new int[] { -android.R.attr.state_focused,
android.R.attr.state_selected,
-android.R.attr.state_pressed}, ColorDrawable(yourBackgroundColor));
如果您的视图未聚焦,选择但未按下,则此时将应用颜色。
答案 1 :(得分:1)
StateListDrawable states = new StateListDrawable();
int yourBackgroundColor = Color.parseColor("#FFFFFF");
// Add specific color when your view has state 'pressed'
states.addState(new int[] {android.R.attr.state_pressed},
new ColorDrawable(yourBackgroundColor));
// Add other states wanted and associated drawable
// ...
// As StateListDrawable extend Drawable, you can use it as background for exemple
yourView.setBackground(states);