If you want o move a view on Android, you should implemts OnTouchListener.
In your layout you can define a view, in this case we use ImageView. But You can use any view.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" tools:showIn="@layout/activity_main" android:id="@+id/content_main_relative_layout" android:background="@android:color/holo_blue_light"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/activity_main_move_the_view" /> <ImageView android:id="@+id/content_main_image_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/ic_dialog_info"/> </RelativeLayout>
Now in your activity when you implement View.OnTouchListener, In this listener you have different events, we use two (ACTION_DOWN and ACTION_MOVE) but you can use anyone.
public class MainActivity extends AppCompatActivity implements View.OnTouchListener{ ImageView mImageView; ViewGroup mRoot; private int mXDelta; private int mYDelta; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRoot = (RelativeLayout)findViewById(R.id.content_main_relative_layout); mImageView = (ImageView) findViewById(R.id.content_main_image_view); mImageView.setOnTouchListener(this); } @Override public boolean onTouch(View v, 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) mImageView.getLayoutParams(); mXDelta = x - lParams.leftMargin; mYDelta = y - lParams.topMargin; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_DOWN: case MotionEvent.ACTION_POINTER_UP: break; case MotionEvent.ACTION_MOVE: RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mImageView.getLayoutParams(); layoutParams.leftMargin = x - mXDelta; layoutParams.topMargin = y - mYDelta; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; mImageView.setLayoutParams(layoutParams); break; } mRoot.invalidate(); return true; } }
Also you can check the complete code in GitHub