Michael Muesch
Michael Muesch

Reputation: 173

OnItemClickListener and Custom OnTouchListener

I have a list of views on a list view that I would like to click on and have the OnItemClickListener get triggered. Though at the same time I want to be able to swipe each view and have a custom action occur. This means that I had to create our own OnTouchEvent for each view when it is made in the ArrayAdapter.

Is there a way to have both of those working together, so that I can have a custom action such as swiping an item and clicking on the item occur easily

Upvotes: 4

Views: 502

Answers (2)

Vikas
Vikas

Reputation: 4301

You class can implement both View.OnTouchListener, AdapterView.OnItemClickListener

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    if(motionEvent.getAction() == MotionEvent.ACTION_UP){
        Log.d(TAG, "ontouch: UP");

     **// Here you can figure if it was simple item click event.
        // We return false only when user touched once on the view. 
        // this will be handled by onItemClick listener.**

        if(lastAction == -1){
            lastAction = MotionEvent.ACTION_UP;
            view.clearFocus();
            return true;
        }
        return false;
    }
    else if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
        Log.d(TAG, "ontouch: DOWN");
        return false;
    }
    else {
        // This is all action events. 
        lastAction = -1;
        return true;
    }
}



@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     // We come here after onTouch event figured out that its a simple touch event and needs to be handled here.
    }

Upvotes: 1

Aswin Kumar
Aswin Kumar

Reputation: 5278

This is very similar to how android Recent Activities are handled - you know, they show a list of all recently opened apps, they can be swiped to remove, or clicked to open. Check out their code, I think you'll get a pretty good idea: https://github.com/android/platform_frameworks_base/tree/master/packages/SystemUI/src/com/android/systemui/recent

Upvotes: 3

Related Questions