Android ListView running an event on Item Long Click Release

后端 未结 2 765
心在旅途
心在旅途 2020-12-17 04:33

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

相关标签:
2条回答
  • 2020-12-17 05:15

    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;
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-17 05:31

    Take a look here () (mainly here, you should be looking for ACTION_UP):

    public static final int ACTION_UP

    Added in API level 1 getAction() value: the key has been released.

    Constant Value: 1 (0x00000001)

    Something like:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.ACTION_UP) {
            // do something on ACTION_UP.
            return true;
        }
    
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
提交回复
热议问题