Why can not I use setOnClickListener and setOnTouchListener in my program? OnTouchListener works well, but I cen't run new activity? what am I doing wrong?
for (final ShopCategory category : gallery.getShopCategories()) {
final Button button = new Button(this);
// ... etc
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);
You can do it better with using drawable selector to change button's show state rather than listen touch event. (create a selector xml file in res/drawable, for example "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>
now edit your code like this:
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);
}
Quick guess here. But try returning false in your onTouch. Returning true in the ActionDown means that you handled the event and no further processing is necessary. So if ActionDown is handled, onClick never happens.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.