Monodroid - 使用Touch事件拖动视图?

时间:2011-09-26 10:22:12

标签: touch drag relativelayout xamarin.android absolutelayout

我想拖动一个视图。到目前为止,我尝试使用LinearLayout和margin以及AbsoluteLayout。

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的工作版本(它是在链接网站中为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 个答案:

答案 0 :(得分:2)

您应该像示例here中那样进行操作。不要忘记阅读文章中的所有要点。