Hello,
Welcome to our Microsoft Q&A platform!
I have an imageview and i would like to drag and drop
If you want to drag or drop image in the xamarin.android, we can achieve it by ImageView's SetOnTouchListener
. Then detect MotionEventActions.Move
event, we can set the X, Y position in the RelativeLayout.
Here is demo code.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
//Get the screensize
DisplayMetrics displaymetrics = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics(displaymetrics);
int screenWidth = displaymetrics.WidthPixels;
int screenHeight = displaymetrics.HeightPixels;
SetContentView(Resource.Layout.activity_main);
ImageView imageView1 = FindViewById<ImageView>(Resource.Id.imageView1);
imageView1.SetOnTouchListener(new MyTouchListener(imageView1, screenWidth, screenHeight));
}
Here is MyTouchListener.cs
.
internal class MyTouchListener : Java.Lang.Object, View.IOnTouchListener
{
public MyTouchListener(ImageView imageView1, int screenWidth, int screenHeight)
{
ImageView1 = imageView1;
ScreenWidth = screenWidth;
ScreenHeight = screenHeight;
}
public ImageView ImageView1 { get; }
public int ScreenWidth { get; }
public int ScreenHeight { get; }
public bool OnTouch(View v, MotionEvent e)
{
var layoutParams1 = (RelativeLayout.LayoutParams)ImageView1.LayoutParameters;
// throw new System.NotImplementedException();
switch (e.ActionMasked)
{
case MotionEventActions.Down:
break;
case MotionEventActions.Move:
int x_cord = (int) e.RawX;
int y_cord = (int)e.RawY;
if (x_cord > ScreenWidth) {
x_cord = ScreenWidth;
}
if (y_cord > ScreenHeight) {
y_cord = ScreenHeight;
}
//You can adjust the Image postion when you are draging.
layoutParams1.LeftMargin = x_cord ;
layoutParams1.TopMargin = y_cord-55 ;
ImageView1.LayoutParameters=layoutParams1;
break;
default:
break;
}
return true;
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.