Android中TextView中background实现点击后换一种样式
时间: 2023-06-18 14:05:34 浏览: 45
在Android中,可以通过设置TextView的不同状态下的背景来实现点击后换一种样式的效果。具体实现步骤如下:
1. 首先,定义两个背景drawable,一个是普通状态下的背景,一个是点击状态下的背景,例如:
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/normal_bg" android:state_pressed="false"/>
<item android:drawable="@color/pressed_bg" android:state_pressed="true"/>
</selector>
```
其中,normal_bg和pressed_bg是两个颜色值,分别表示普通状态下和点击状态下的背景颜色。
2. 然后,在TextView的布局文件中设置background属性为上面定义的selector,例如:
```
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="@drawable/my_selector"/>
```
其中,my_selector是上面定义的selector的名称。
3. 最后,在Java代码中设置TextView的Clickable属性为true,以启用点击事件,例如:
```
TextView textView = findViewById(R.id.text_view);
textView.setClickable(true);
```
这样,当用户点击TextView时,背景会自动切换为点击状态下的背景,松开手指后又会恢复为普通状态下的背景。