android点击按钮图标变色
时间: 2023-02-06 17:56:49 浏览: 65
在 Android 中,要让按钮图标在点击时变色,可以使用 selector 来实现。
首先,需要准备两张图片,分别代表按钮图标的默认状态和点击后的状态。然后在 res/drawable 文件夹中创建一个 selector 文件,代码如下:
```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_icon_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/button_icon_default" />
</selector>
```
其中,@drawable/button_icon_pressed 和 @drawable/button_icon_default 分别代表点击后的图片和默认图片。
最后,可以将这个 selector 设置为按钮的背景,代码如下:
```
button.setBackgroundResource(R.drawable.button_icon_selector);
```
这样,当用户点击按钮时,按钮的图标就会变色。
相关问题
androidstudio按钮点击变色
要实现 Android Studio 按钮点击变色的效果,可以通过以下步骤进行操作:
1. 在 res 文件夹下创建一个新的 drawable 资源文件,例如 button_bg.xml。
2. 在该文件中定义按钮点击变色的效果,例如:
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorPrimaryDark" />
<item android:drawable="@color/colorPrimary" />
</selector>
```
这里使用了 selector 标签,表示根据按钮的状态来选择显示哪个 drawable。当按钮被按下时,显示 colorPrimaryDark 颜色;否则显示 colorPrimary 颜色。
3. 将该 drawable 应用到按钮的 background 属性中,例如:
```
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:background="@drawable/button_bg" />
```
这样,当用户点击按钮时,按钮的背景颜色就会变为 colorPrimaryDark。
希望这些步骤可以帮助到你实现 Android Studio 按钮点击变色的效果。
android微信点击按钮变色
在 Android 微信中,如果想让点击按钮变色,你可以在布局文件中使用 `android:background` 属性来设置按钮的背景颜色。
例如,你可以在布局文件中声明一个按钮,并使用 `android:background` 属性设置为红色:
```
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text="Click me" />
```
当你在微信中点击这个按钮时,按钮的背景颜色就会变成红色。
你也可以使用代码动态更改按钮的背景颜色。例如,你可以在点击按钮时使用 `setBackgroundColor()` 方法来更改按钮的背景颜色:
```
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
button.setBackgroundColor(Color.RED);
}
});
```
这样,你就可以在点击按钮时使按钮的背景颜色变成红色。