【发布时间】:2016-05-27 07:48:03
【问题描述】:
我创建了一个Button b,其背景颜色为黑色。当我点击它时,我希望它的颜色仅在我用手指放在它上面时变为绿色,即我一直专注于它。
【问题讨论】:
-
请提供您所做的工作,并告诉我们您遇到的问题。
-
这里同样的问题得到了明确的回答stackoverflow.com/questions/3882064/…
标签: android
我创建了一个Button b,其背景颜色为黑色。当我点击它时,我希望它的颜色仅在我用手指放在它上面时变为绿色,即我一直专注于它。
【问题讨论】:
标签: android
在您的按钮中使用选择器。
<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>
【讨论】:
您需要使用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;
}
});
【讨论】:
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));
}
}
};
【讨论】:
使这个 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>
【讨论】: