我创建了一个背景色为黑色的按钮。当我点击它时,我希望它的颜色只在我手指按住它的时间内改变为绿色,即我保持对它的关注。
我创建了一个背景色为黑色的按钮。当我点击它时,我希望它的颜色只在我手指按住它的时间内改变为绿色,即我保持对它的关注。
<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;
}
});
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 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>