2016-05-27 80 views
2

我创建了一个Button b,其背景色为黑色。当我点击它时,我希望它的颜色只在我有手指的时候变成绿色,即我一直关注它。如何更改android studio中按钮水龙头上按钮的颜色

+0

请提供您所做的工作,并告诉我们您遇到问题的位置。 – Flummox

+0

看到这个:http://stackoverflow.com/a/1726352/5250273 –

+1

这里是相同的问题回答清楚http://stackoverflow.com/questions/3882064/how-to-change-color-of-button-in- android-when-clicked – fReeTaSte

回答

5

使用在您的按钮选择听。

<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> 
0

ACTION_UP - >的压制手势完成时,运动包含 最终释放位置以及由于 任何中间点最后向下或移动事件。

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

+0

as getColor()is used to use,btn.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.colorAccent)); @ Diptangsu Goswami –

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; 
    } 
}); 
+0

而不是像这样注册触摸事件,我们可以使选择器可绘制使用多种颜色/绘制不同的状态。 – seema

0

使这个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>