public class DeskSelection extends AppCompatActivity {
private ImageView mImageView;
private ViewGroup mMoveLayout;
private int mX;
private int mY;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.desk_selection);
mMoveLayout = (ViewGroup) findViewById(R.id.move);
mImageView = mMoveLayout.findViewById(R.id.imageView);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
mImageView.setClickable(true);
mImageView.setFocusableInTouchMode(true);
mImageView.requestFocus();
mImageView.setLayoutParams(layoutParams);
mImageView.setOnTouchListener(new View.OnTouchListener() {
@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) v.getLayoutParams();
mX = X - lParams.leftMargin;
mY = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = X - mX;
layoutParams.topMargin = Y - mY;
layoutParams.rightMargin = -250;
layoutParams.bottomMargin = -250;
v.setLayoutParams(layoutParams);
break;
}
return true;
}
});
}
}
код xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id = "@+id/move"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#7EB2EA"
android:clickable="true"
android:focusable="true"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="110dp"
android:layout_height="134dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="-99dp"
android:layout_marginTop="106dp"
android:layout_marginEnd="491dp"
android:layout_marginBottom="171dp"
android:contentDescription="@string/card1"
app:srcCompat="@drawable/cardsa1" />
</RelativeLayout>