Android中TextView中background实现点击后改变样式
时间: 2023-06-18 09:05:47 浏览: 41
可以通过设置TextView的Selector来实现点击后改变样式的效果。Selector是一个XML文件,可以根据不同的状态来设置不同的样式。
下面是一个例子:
首先,创建一个名为“textview_selector.xml”的XML文件,代码如下:
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/gray" />
<item android:drawable="@color/white" />
</selector>
```
这个Selector设置了两个状态,一个是当TextView被按下时,背景色为灰色,另一个是默认状态,背景色为白色。
接着,在布局文件中将TextView的background设置为这个Selector:
```
<TextView
android:id="@+id/my_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="@drawable/textview_selector" />
```
这样就完成了TextView点击后改变样式的效果了。
相关问题
Android中TextView中background实现点击改变样式
你可以使用 `StateListDrawable` 来实现在 TextView 点击时改变背景的样式。下面是一个示例:
1. 首先,在 `res/drawable` 目录下创建一个名为 `background_selector.xml` 的文件,用于定义 `StateListDrawable`:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/pressed_background" />
<item android:drawable="@drawable/normal_background" />
</selector>
```
上面的代码定义了两个状态:`state_pressed` 表示按下时的状态,`drawable` 表示对应的背景。当 TextView 被按下时,会显示 `pressed_background` 背景;否则,显示 `normal_background` 背景。
2. 接着,在 `res/drawable` 目录下创建 `pressed_background.xml` 和 `normal_background.xml` 两个文件,分别表示按下和普通状态下的背景。这里以红色和蓝色为例:
`pressed_background.xml`:
```xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
```
`normal_background.xml`:
```xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#0000FF" />
</shape>
```
3. 最后,在布局文件中,将 TextView 的 background 属性设置为 `background_selector` 即可:
```xml
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="@drawable/background_selector" />
```
这样,当用户点击 TextView 时,背景颜色会从蓝色变为红色,松开时又会变回蓝色。
Android中TextView中background实现改变样式
在Android中,可以使用`TextView`的`android:background`属性来改变其背景样式。以下是一些示例:
1. 设置纯色背景
```
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text="Hello World!" />
```
2. 设置圆角矩形背景
```
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/round_rect_background"
android:text="Hello World!" />
```
其中,`@drawable/round_rect_background`是一个自定义的背景资源,定义如下:
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp" />
<solid android:color="#FF0000" />
</shape>
```
这个资源定义了一个圆角矩形,并且背景颜色为红色。
3. 设置图片背景
```
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background_image"
android:text="Hello World!" />
```
其中,`@drawable/background_image`是一个图片资源。