Android笔记-设置textview的press效果

来源:互联网 发布:safari for windows 7 编辑:程序博客网 时间:2024/05/21 23:45

工作的第一篇技术笔记

如何在textview上设置button一样的press效果,默认灰色, press高亮是蓝色

有如下两种方法:

1.​通过xml定义selector:

在res/drawable 中定义textselector.xml如下
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:state_pressed="true"        android:drawable="@android:color/holo_blue_bright" //press的状态        />    <item        android:drawable="@android:color/darker_gray" // 平时的状态        /></selector>

android:drawable的后面也可以是你自定义的一个state,例如state_pressed.xml,下面代码表示是方形,填充色为蓝色:
<?xml version="1.0" encoding="UTF-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle">    <solid android:color="@android:color/holo_blue_bright" /></shape>
将item tag里面的android:drawable后面替换成@drawable/state_pressed.

然后在定义textview的xml中设置上面定义的selector为background
 <TextView        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:padding="4dp"        android:text="SCREEN PINNING"        android:textSize="20sp"        android:textColor="@android:color/holo_orange_light"        android:background="@drawable/textselector"> </TextView>


2.通过StateListDrawable在程序里面设置:

定义一个StateListDrawable​如下,
ColorDrawable drawable = new ColorDrawable();// 平时的状态drawable.setColor(Color.GRAY);int pressed = android.R.attr.state_pressed; // 前面加个负号对于xml里面false 值int selected = android.R.attr.state_selected;int focused = android.R.attr.state_focused;
StateListDrawable listDrawable = new StateListDrawable();ColorDrawable lHighLightDrawable = new ColorDrawable(); //高亮状态lHighLightDrawable.setColor(Color.rgb(106, 170, 234));
//下面的状态都要加上listDrawable.addState(new int[] {pressed}, lHighLightDrawable);listDrawable.addState(new int[] {-focused, selected, -pressed}, lHighLightDrawable);listDrawable.addState(new int[] {-focused, -selected, -pressed}, drawable);listDrawable.addState(new int[] {focused, -selected, -pressed}, drawable);listDrawable.addState(new int[] {focused, selected, -pressed}, drawable);
然后将listDrawable设置在textview上,别忘了开启textview的focus,press, focusInTouchMode, 代码如下,
text.setClickable(true);text.setFocusable(true);text.setFocusableInTouchMode(true);   text.setBackgroundDrawable(listDrawable);

以上两种方法亲测有效。
可以参考 http://blog.csdn.net/qinjuning/article/details/7474827, 里面写的很详细

0 0