2012-10-05 43 views
4

我有一个ListView,里面有自定义元素。我想为每个元素创建选择器。选择器本身不会很复杂,因为它们只需处理背景颜色,而项目悬停/选定/等等。然而,这些选择器的颜色必须来自外部来源,我需要能够从变量中设置它们,所以一些简单的静态代码将无法做到。
动态定义和使用选择器

  1. 如何与所有它`参数编程的方式定义部门?
  2. 如何以编程方式将该选择器分配给特定视图?

回答

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
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);