android studio中button按钮怎么改按前和按后的颜色
时间: 2024-06-12 19:05:28 浏览: 15
可以通过设置按钮的背景颜色或者使用selector来实现按钮的按前和按后的颜色。具体的实现方式如下:
1. 设置按钮背景颜色
可以通过设置按钮的背景颜色来改变按钮的按前和按后的颜色。可以使用以下代码来实现:
```
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@color/button_color" />
```
在这个例子中,我们使用了一个颜色资源文件来设置按钮的背景颜色。在res/values/colors.xml文件中添加以下代码:
```
<resources>
<color name="button_color">#FF4081</color>
</resources>
```
这样就可以将按钮的背景颜色设置为粉红色了。
2. 使用selector实现按钮按前和按后的颜色
可以使用selector来实现按钮按前和按后的颜色。selector是一个XML文件,用于根据不同的状态来选择不同的Drawable。可以使用以下代码来创建一个selector:
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/button_pressed_color" />
<item android:drawable="@color/button_normal_color" />
</selector>
```
在这个例子中,我们设置了两个item,一个是按钮被按下时的状态,另一个是按钮正常状态的颜色。在res/values/colors.xml文件中添加以下代码:
```
<resources>
<color name="button_normal_color">#FF4081</color>
<color name="button_pressed_color">#E91E63</color>
</resources>
```
这样就可以将按钮的按前和按后的颜色分别设置为粉红色和洋红色了。最后在布局文件中使用以下代码来设置按钮的背景:
```
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:background="@drawable/button_selector" />
```
这样就可以实现按钮按前和按后的颜色的改变了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)