Monodroid - 拖动视图与触摸事件?

问题描述:

我想拖动一个视图。直到现在,我用LinearLayout和边距以及AbsoluteLayout来试用它。Monodroid - 拖动视图与触摸事件?

AbsoluteLayout例如:

button.Touch = (clickedView, motionEvent) => 
{ 
    Button b = (Button)clickedView; 
    if (motionEvent.Action == MotionEventActions.Move) 
    {      
     AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(100, 35, (int)motionEvent.GetX(), (int)motionEvent.GetY()); 
     b.LayoutParameters = layoutParams;      
    } 
    return true; 
}; 

在我想我得到了一个古玩行为每一个案件。这是为什么。我拖着的视图跟随着我的手指,但总是在两个位置之间跳跃。其中一个是我的手指,另一个是我的手指左上角。如果我只是将我的当前位置写入文本视图(而不移动视图),则坐标的行为与预期相同。但如果我也在移动视图,他们又会跳起来。 我该如何避免这种情况?

编辑:我用我的问题的声音评论,以实施monodroid工作draging(这是在Java/Android SDK在链接的网站完成)。也许别人有兴趣做一些日子,所以这里是我的解决方案:

[Activity(Label = "Draging", MainLauncher = true, Icon = "@drawable/icon")] 
public class Activity1 : Activity 
{ 
    private View selectedItem = null; 
    private int offset_x = 0; 
    private int offset_y = 0; 

    protected override void OnCreate(Bundle savedInstanceState) 
    { 
     base.OnCreate(savedInstanceState); 
     SetContentView(Resource.Layout.Main); 

     ViewGroup vg = (ViewGroup)FindViewById(Resource.Id.vg); 
     vg.Touch = (element, motionEvent) => 
     { 
      switch (motionEvent.Action) 
      { 
       case MotionEventActions.Move: 
        int x = (int)motionEvent.GetX() - offset_x; 
        int y = (int)motionEvent.GetY() - offset_y; 
        int w = WindowManager.DefaultDisplay.Width - 100; 
        int h = WindowManager.DefaultDisplay.Height - 100; 
        if (x > w) 
         x = w; 
        if (y > h) 
         y = h; 
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
         new ViewGroup.MarginLayoutParams(
          LinearLayout.LayoutParams.WrapContent, 
          LinearLayout.LayoutParams.WrapContent)); 
        lp.SetMargins(x, y, 0, 0); 
        selectedItem.LayoutParameters = lp; 
        break; 
       default: 
        break; 
      } 
      return true; 
     }; 

     ImageView img = FindViewById<ImageView>(Resource.Id.img); 
     img.Touch = (element, motionEvent) => 
     { 
      switch (motionEvent.Action) 
      { 
       case MotionEventActions.Down: 
        offset_x = (int)motionEvent.GetX(); 
        offset_y = (int)motionEvent.GetY(); 
        selectedItem = element; 
        break; 
       default: 
        break; 
      } 
      return false; 
     }; 
    }   
} 
+1

http://www.edumobile.org/android/android-beginner-tutorials/drag-and-drop-ui-element/ – mironych

你应该做如上例here。不要忘记阅读文章中的所有要点。

+0

同时我也发现这篇文章,并切换到该解决方案,这是多变多变。 – andineupert