Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView running an event on Item Long Click Release

I'm using an OnItemClickListener and an OnItemLongClickListener in a ListView, now i'm searching a way to detect the release action after the OnItemLongClick, what's the best way to accomplish this?

like image 832
Luca Vitucci Avatar asked Jan 12 '23 16:01

Luca Vitucci


1 Answers

While i accepted @g00dy answer i found that this solution fits my needs better, and keeps my code in one place.

inside the Activity where i setup the listView i'm doing this:

MyOnLongClickListener myListener = new MyOnLongClickListener(this);
listView.setOnItemLongClickListener(myListener);
listView.setOnTouchListener(myListener.getReleaseListener());

all the magic happens inside "MyOnLongClickListener":

public class MyOnLongClickListener implements AdapterView.OnItemLongClickListener {

    private View.OnTouchListener mReleaseListener = new OnReleaseListener();
    private boolean mEnabled = false;
    private Context mContext;

    public MyOnLongClickListener(Context context) {
        mContext = context;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(mContext, "OnLongClick", Toast.LENGTH_SHORT).show();
        mEnabled = true;
        return true;
    }

    /**
     * Returns a listener for the release event.
     * @return
     */
    public View.OnTouchListener getReleaseListener() {
        return mReleaseListener;
    }

    /**
     * Listener for the Release event.
     */
    private class OnReleaseListener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if(motionEvent.getAction() == android.view.MotionEvent.ACTION_UP) {
                if(mEnabled) {
                    Toast.makeText(mContext, "Release", Toast.LENGTH_SHORT).show();
                    /* Execute... */
                    mEnabled = false;
                    return true;
                }
            }
            return false;
        }
    }

}
like image 101
Luca Vitucci Avatar answered Jan 15 '23 06:01

Luca Vitucci