android selector(如对TextView点击样式改变) - perfect亮

selector

1.selector 从单词的意思来说:选择者,选择器,就是对你的目标的控制。

从API来说:

A controller for the selection of SelectableChannel objects. Selectable channels can be registered with a selector and get a SelectionKey that represents the registration. The keys are also added to the selector’s key set. Selection keys can be canceled so that the corresponding channel is no longer registered with the selector.

By invoking the select method, the key set is checked and all keys that have been canceled since last select operation are moved to the set of canceled keys. During the select operation, the channels registered with this selector are checked to see whether they are ready for operation according to their interest set

其实API 说了那么就是在解释单词的意思。

selector主要是用在ListView的item单击样式和TextView和Button的点击样式。

2.现在对他的一些属性进行介绍

属性介绍:

android:state_selected选中
android:state_focused获得焦点
android:state_pressed点击
android:state_enabled设置是否响应事件,指所有事件

3.下面通过例子来说一下selector对TextView和ListView的设置:

TextView:

  1).在res下创建一个drawable文件夹用于装textselector.xml ,对点击样式的定义放在这里面

  2).values下定义colors.xml文件,将颜色资源放在里面

  3).将textselector.xml资源加载到TextView上,

textselector.xml

1 <?xml version="1.0" encoding="utf-8"?>
2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
3     <item android:state_pressed="true" android:color="@color/red"></item>  <!-- 点击后的字体颜色 -->
4     <item android:color="@color/gray"></item>    <!-- 默认字体颜色 -->
5 </selector>

activity.xml

复制代码

1   <TextView
2         android:id="@+id/text"
3         android:layout_width="wrap_content"    
4         android:layout_height="wrap_content"
5         android:text="@string/hello_world" 
6         android:textColor="@drawable/textselector"   
7         android:textSize="15dp"
8         />    <!-- textColor对 selector引用 -->

复制代码
这样运行程序去点击textview是不会看到textview颜色改变的,这是因为还没有给TextView添加按钮监听事件,就算事件不取执行什么功能都必须去设置(或者给TextView设置属性android:clickable = true,也可以)

1 TextView text = (TextView)findViewById(R.id.text);
2 text.setOnClickListener(null);
终上所述:就有效果了

下面会说说ListView:
(1)在ListView中添加如下属性代码

android:listSelector="@drawable/mylist_view"  
<android:listSelector="@drawable/mylist_view"  />

(2)在ListView的item界面中添加如下属性代码

<android:background="@drawable/mylist_view" />

(3)利用JAVA代码直接编写

1 Drawable drawable = getResources().getDrawable(R.drawable.mylist_view); 
2 
3 listView.setSelector(drawable);  

Button的类似就不说了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值