Vlatego
Vlatego

Reputation: 608

OnTouchListener on GridView elements

I'm trying to develop a kind of applications drawer. I use a gridview with an adapter to draw the icons. I'd like to implement drap&drop on them so I wrote an ontouchlistener that works fine on other elements, but has some problem with the icon in the gridview...

When I long press on an icon, i can drag it horizontally but only for some pixel verticaly, than the motionevent give MotionEvent.ACTION_CANCEL,the drag stops and the gridview begin to scroll. How can I avoid it? I tryed gridview.setEnable(false), in order to make unscrollable the gridview, but the drag stops as before..

Can someone help me? Here some code if it can help...

    @Override
public boolean onTouch(View view, MotionEvent me) {
    int action = me.getAction();

    switch(action){

    case MotionEvent.ACTION_DOWN:
        status = START_DRAGGING;
        params = new RelativeLayout.LayoutParams(dim,dim);
        params.leftMargin=(int) me.getRawX()-60;
        params.topMargin= (int) me.getRawY()-90;
        parenty=bglayout.getHeight();
        view.setDrawingCacheEnabled(true);
        image.setImageBitmap(view.getDrawingCache()); 
        bglayout.addView(image, params); 
        grview.setOnItemSelectedListener(null);
        break;
    case MotionEvent.ACTION_CANCEL: 
    case MotionEvent.ACTION_UP: 
        status = STOP_DRAGGING;
        Log.v("Drag", "Stopped Dragging");
        bglayout.removeView(image);
        break;

    case MotionEvent.ACTION_MOVE:
            if (status == START_DRAGGING) {
                System.out.println("Dragging");
                params = new RelativeLayout.LayoutParams(dim,dim);
                params.leftMargin= (int) Math.min(me.getRawX()-dim/2, bglayout.getWidth()-dim) ;
                params.topMargin= (int) Math.min(me.getRawY()-dim/2, bglayout.getHeight()-dim) ;
                Log.v("DRAG", params.leftMargin + " " + params.topMargin);
                image.setLayoutParams(params);
                image.invalidate();

            } 
        }
        return false;
    }

Upvotes: 0

Views: 1842

Answers (1)

Siebn
Siebn

Reputation: 11

You should try to call requestDisallowInterceptTouchEvent() on the parent of the view during every MotionEvent.ACTION_DOWN or MotionEvent.ACTION_MOVE.

This code was extracted from android.widget.SeekBar:

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            attemptClaimDrag();
            break;

        case MotionEvent.ACTION_MOVE:
            attemptClaimDrag();
            break;
    }
    return super.onTouchEvent(event);
}


private void attemptClaimDrag() {
    ViewParent parent = getParent();
    if (parent != null) {
        parent.requestDisallowInterceptTouchEvent(true);
    }
}

Upvotes: 1

Related Questions