---
title: "android自定义TextView点击效果"
author: "泽.."
date: "2014-11-29T10:19:36Z"
tags: []
categories: ["移动开发"]
slug: "android-textview"
draft: false
lastmod: "2014-11-29T10:48:19Z"
id: 2161737
url: "https://dzc.iteye.com/blog/2161737"
---

在android开发中，按钮是经常要用到的，要做到按下去有点击效果的，需要给按钮定义一个可点击的drawable。而且，一般我都不会去用button控件，我一般都是用TextView当按钮的。

关于drawable的定义，可参考另一篇文章[http://dzc.iteye.com/blog/2161759](/blog/2161759)

1.首先，我们要自己定义一个可点击的drawable，在res下的drawable文件夹新建一个xml文件selector\_bg.xml

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;selector xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)" &gt;  
    &lt;item android:state\_pressed="true" android:drawable="@drawable/pressed"/&gt;  
    &lt;item android:drawable="@drawable/normal"/&gt;  
&lt;/selector&gt;

// &lt;item android:state\_pressed="true" android:drawable="@drawable/pressed"/&gt; 这一行代码的作用是定义当用户按下的时候显示pressed   drawable，pressed可以是一张图片，也可以是一个xml文件

//&lt;item android:drawable="@drawable/normal"/&gt;  这一行定义的是当用户什么都没做的时候的drawable

 

2.我们可以在TextView中指定android:background="@drawable/selector\_bg"

这样，TextView就具有了点击时和没点击时显示不同背景的效果

 

3.当然，对于TextView的text我们也可以做成这种效果 ，在res下新建一个color的文件夹，新建一个xml文件，selector\_color\_bg.xml

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;selector xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"&gt;  
    &lt;item android:state\_pressed="true" android:color="@color/color\_pressed"/&gt;  
    &lt;item android:color="@color/color\_normal"/&gt;  
&lt;/selector&gt;

其中，color\_pressed和color\_normal是res/values/colors.xml中定义的颜色

4.在TextView中为text指定颜色android:textColor="@color/selector\_user\_sign\_up\_button\_text\_color"

这样，文字也就会有点击反馈