【问题标题】:how to make change a button background color in ontouchListener?如何在 ontouchListener 中更改按钮背景颜色?
【发布时间】:2021-04-15 12:51:36
【问题描述】:

我想更改 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;
        }

    });

【问题讨论】:

  • 你试过 setBackgroundTint() 吗? , 另外我建议你使用 setOnClickListener 代替,如果触摸不是一个用例?
  • 我用 ontouch 和 onclick 监听器尝试了 setBackgroundTint() 但我收到了来自 android studio 的消息:无法解析按钮 @oguzhanarslan 中的 setbackgroundTint
  • 很抱歉,您可以在这里找到如何以编程方式将色调应用于按钮stackoverflow.com/questions/29801031/…

标签: android android-studio


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2018-09-02
    • 2021-06-22
    • 2015-04-03
    相关资源
    最近更新 更多