[英]How to use setOnClickListener and setOnTouchListener + for
为什么我不能在程序中使用setOnClickListener和setOnTouchListener? OnTouchListener运作良好,但是我没有运行新活动吗? 我究竟做错了什么?
for (final ShopCategory category : gallery.getShopCategories()) {
final Button button = new Button(this);
// ...等等
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
runNewActivity(gallery.getShops(), category);
}
});
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN ) {
button.setTextColor(Color.parseColor("#333333"));
button.setBackgroundColor(Color.parseColor("#ffcc33"));
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP ) {
button.setTextColor(Color.WHITE);
button.setBackgroundColor(Color.parseColor("#333333"));
}
return false;
}
});
categoriesButtonsLL.addView(button);
使用可绘制选择器来更改按钮的显示状态,而不是侦听触摸事件,可以做得更好。 (在res / drawable中创建选择器xml文件,例如“ button_bg.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="@drawable/button_pressed" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/button_focused" /> <!-- focused -->
<item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>
现在像这样编辑您的代码:
for (final ShopCategory category : gallery.getShopCategories()) {
final Button button = new Button(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
runNewActivity(gallery.getShops(), category);
}
});
button.setBackgroundResource(R.drawable.button_bg);
categoriesButtonsLL.addView(button);
}
在这里快速猜测。 但是,请尝试在您的onTouch中返回false。 在ActionDown中返回true表示您已处理该事件,无需进一步处理。 因此,如果处理了ActionDown,则不会发生onClick。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.