android - 如何在 ontouchListener 中更改按钮背景颜色?
问题描述
我想更改 ontouchListener 中的背景颜色,我可以更改 textColor 但背景颜色保持不变:这是我的代码:
Button usd=findViewById(R.id.button_divide);
Button cdf=findViewById(R.id.button_multiply);
usd.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
SharedPreferences.Editor editor=sharedPref.edit();
editor.putString("currency","USD");
editor.apply();
usd.setBackgroundColor(Color.parseColor("#515de1"));
usd.setTextColor(Color.WHITE);
cdf.setBackgroundColor(Color.WHITE);
cdf.setTextColor(Color.parseColor("#515de1"));
return false;
}
});
解决方案
我最好使用selector
代替代码
<Button
android:id="@+id/myButton"
android:background="@drawable/selector_my_button"
android:layout_width="100dp"
android:layout_height="36dp"
android:text="My Button" />
和selector_my_button.xml是这样的
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/white"/> <!-- pressed -->
<item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
<item android:drawable="@color/black"/> <!-- default -->
</selector>
推荐阅读
- apache-poi - 在 Apache POI 中对工作表进行分组(和取消分组)
- php - 如何让脚本在一个月后运行?
- algorithm - 机器学习算法更新值
- javascript - 将 html 元素转换为 javascript 数组,然后将它们打印回页面
- jmeter - JMeter - 生成对象并添加到数组
- javascript - 如何在元素 ui Vuejs 的 el 表中添加/删除列后证明列的合理性?
- rotation - 在easeljs/tweenjs 中手动旋转
- java - JavaFX、FXML、登录表单和更改阶段或场景
- azure-devops - 在 MTM > 实验室中心 > 实验室 > 环境中出现错误(生成 XML 文档时出错)
- nginx - 由于 502 Bad Gateway 将 /var/www/html/ 更改为 /var/www/