【问题标题】:Dynamically defining and using selectors动态定义和使用选择器
【发布时间】:2012-10-05 21:09:23
【问题描述】:

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

  1. 如何以编程方式使用所有参数定义扇区?
  2. 如何以编程方式将该选择器分配给特定视图?

【问题讨论】:

    标签: java android selector


    【解决方案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);
    

    您可以在 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));
    

    这一次,如果您的视图未聚焦、被选中且未按下,则将应用颜色。

    【讨论】:

      【解决方案2】:
      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-15
        • 1970-01-01
        • 2023-04-06
        • 2020-06-25
        • 2015-07-10
        • 1970-01-01
        相关资源
        最近更新 更多