动态定义和使用选择器 [英] Dynamically defining and using selectors

查看:152
本文介绍了动态定义和使用选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 to handle only background color while item is hovers/selected/etc. However colors for those selectors have to come from external source that is I need to be able to set them from variables, so some simple static code will not do.


  1. 如何以编程方式定义包含所有参数的扇区?

  2. 如何以编程方式将选择器分配给特定视图?

  1. How to define sector with all it`s parameters programmatically?
  2. How to assign that selector programmatically to a specific view?


推荐答案

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-列表resource.html )。
对于每种状态组合,您可以设置特定和动态可绘制。

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(new int[] { -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.

这篇关于动态定义和使用选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆