首页 > 解决方案 > 如何在 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;
        }

    });

标签: androidandroid-studio

解决方案


我最好使用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>

推荐阅读