Redraw the view during MotionEvent.ACTION_MOVE in onTouchEvent ()

I created my own component that extends RelativeLayout , inside it I have a field of type View that fits with the fields:

enter image description here

The blue box represents my parental view, and the red circle represents the child.

Now I want to allow the user to move this red circle by moving my finger across the screen. This is my onTouchEvent() method:

 @Override public boolean onTouchEvent(MotionEvent event) { int eventAction = event.getAction(); switch (eventAction) { case MotionEvent.ACTION_DOWN: // finger touches the screen break; case MotionEvent.ACTION_MOVE: marginX = (int)event.getX(); marginY = (int)event.getY(); RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)pointer.getLayoutParams(); // pointer is this red circle lp.setMargins(marginX, marginY, 0, 0); break; case MotionEvent.ACTION_UP: // finger leaves the screen break; } return true; } 

But I quickly found that he does not update his position while the user moves his finger across the screen, but instead he does this only when the user releases his finger from the screen. Thus, basically, when I move my finger, the circle remains in one position, but when I stop moving, the circle is drawn in a new position. I tried to use the invalidate() method for both parent and child view, but that didn't help. I guess this may have something to do with the UI thread, but I don't have access to runOnUiThread()' method as it not an Activity`.

EDIT: I passed my activity to the class to use runOnUiThread() . Now my case: ACTION_MOVE looks like this:

 case MotionEvent.ACTION_MOVE: marginX = (int)event.getX(); marginY = (int)event.getY(); activity.runOnUiThread(new Runnable() { public void run() { RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)pointer.getLayoutParams(); lp.setMargins(marginX, marginY, 0, 0); pointer.invalidate(); } }); break; 
+4
source share
2 answers

If it's a simple pointer, you can draw it on Canvas as Drawable :

 @Override protected void onDraw(Canvas canvas) { pointer.setBounds(marginX, marginY, marginX + pointerWidth, marginY + pointerHeight); pointer.draw(canvas); super.onDraw(canvas); } 

And then call invalidate() by pointer in the onTouchEvent() method.

+2
source

I think you need a drag and drop function

See http://www.vogella.com/articles/AndroidDragAndDrop/article.html

+2
source

All Articles