-1

ImageView snap in center with two vertical and horizontal line

I want to put ImageView in the layout and move it with my fingers.Then snap to center when image near to center

  • Does this answer your question? [android: move a view on touch move (ACTION\_MOVE)](https://stackoverflow.com/questions/9398057/android-move-a-view-on-touch-move-action-move) – LethalMaus Jan 05 '21 at 16:07

1 Answers1

0

I found something for you. Let me implement some source code.

 private OnTouchListener onTouchListener() {


return new OnTouchListener() {

   @SuppressLint("ClickableViewAccessibility")
   @Override
   public boolean onTouch(View view, MotionEvent event) {
    
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();

switch (event.getAction() & MotionEvent.ACTION_MASK) {

case MotionEvent.ACTION_DOWN:
 RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) 
 view.getLayoutParams();
 
 xDelta = x - lParams.leftMargin;
 yDelta = y - lParams.topMargin;
 break;
 
case MotionEvent.ACTION_UP:
 Toast.makeText(TouchActivity.this,
   "thanks for new location!", Toast.LENGTH_SHORT)
   .show();
 break;
 
case MotionEvent.ACTION_MOVE:
 RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
   .getLayoutParams();
 layoutParams.leftMargin = x - xDelta;
 layoutParams.topMargin = y - yDelta;
 layoutParams.rightMargin = 0;
 layoutParams.bottomMargin = 0;
 view.setLayoutParams(layoutParams);
 break;
}
mainLayout.invalidate();
return true;
}


};
 }

To run the source code on imageView

imageView.setOnTouchListener(onTouchListener());
  • how to snap ImageView in center of layout? – Mohammadb72 Jan 05 '21 at 20:13
  • @Mohammadb72 `android:gravity='center'` I don't remember. I think it only works for text. OK! lemme implement another code `android:centerVertical='true'` and `android:centerHorizontal='true'`. It only works in `RelativeLayout`. If you are using `LinearLayout` than there's no way to do it. Than, you have `margin` them accurately. –  Jan 05 '21 at 20:35
  • How can i draw lines? – Mohammadb72 Jan 06 '21 at 04:14
  • @Mohammadb72 Visit the [link](https://github.com/Istiakshovon/PaintApplication). I have [advanced paint](https://github.com/Istiakshovon/AdvancedPaintApplication) app also. –  Jan 06 '21 at 04:40