2

我想拖动一个视图。到目前为止,我尝试使用 LinearLayout 和边距以及 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;
        };
    }        
}
4

0 回答 0