Mateusz Ryndak
Mateusz Ryndak

Reputation: 87

How to use setOnClickListener and setOnTouchListener + for

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);

Upvotes: 0

Views: 6645

Answers (2)

UperOne
UperOne

Reputation: 195

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

Upvotes: 2

NameSpace
NameSpace

Reputation: 10177

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.

Upvotes: 1

Related Questions