【问题标题】:How to change color of Button on button tap in android studio [duplicate]如何在android studio中更改按钮点击按钮的颜色[重复]
【发布时间】:2016-05-27 07:48:03
【问题描述】:

我创建了一个Button b,其背景颜色为黑色。当我点击它时,我希望它的颜色仅在我用手指放在它上面时变为绿色,即我一直专注于它。

【问题讨论】:

标签: android


【解决方案1】:

在您的按钮中使用选择器。

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content" android:layout_width="fill_parent"
    android:gravity="center" android:focusable="true"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:background="@android:drawable/list_selector_background" />

这是 list_selector_background 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/green"/> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
    <item android:drawable="@color/black"/> <!-- default -->
</selector>

【讨论】:

    【解决方案2】:

    您需要使用onTouchListener 来监听用户按下按钮(ACTION_DOWN)和用户释放按钮(ACTION_UP)的时间

    b.setOnTouchListener(new OnTouchListener() { 
    
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
           // reset the background color here
            b.setBackgroundColor(Color.GREEN);
    
        }else{ 
           // Change the background color here 
            b.setBackgroundColor(Color.RED);
    
        } 
        return false; 
       } 
    }); 
    

    【讨论】:

    • 代替像这样注册触摸事件,我们可以使用多种颜色/drawables 为不同的状态使选择器可绘制。
    【解决方案3】:

    ACTION_UP --> 按下的手势已经完成,动作包含 最终发布位置以及自 last down 或 move 事件。

    ACTION_DOWN --> 按下手势已经开始,动作包含 初始起始位置。

    你应该在你的按钮上设置一个OnTouchListener

    button.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
                btn.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                btn.setBackgroundColor(getResources().getColor(R.color.white));
            }
        }
    };
    

    查看motion events

    【讨论】:

    • 因为 getColor() 已弃用,您可以使用 btn.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));@Diptangsu Goswami
    【解决方案4】:

    使这个 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/green"/> 
    <item android:drawable="@color/black"/>
    </selector>
    

    【讨论】:

      猜你喜欢
      • 2013-11-08
      • 1970-01-01
      • 2021-07-07
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多