亲宝软件园·资讯

展开

Android View拖拽 Android实现View的拖拽

lanlengran蓝冷然 人气:0

前言

实现View的拖拽,其实原理很简单。无非就是获取手指的位移信息,然后view根据手指的位移信息,移动对应的位置。

首先是获取手机的位移信息就可以根据需求不同分为两种

而移动的方法嘛,也有几种

代码

public class ViewTestActivity extends AppCompatActivity {
  private static final String TAG = "ViewTestActivity";
  private TextView mTv1,mTv2;
  private double lastx,lastY;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_test);
    mTv1= (TextView) findViewById(R.id.tv01);
    mTv1.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        double x=event.getRawX();
        double y=event.getRawY();
        Log.d(TAG, "onTouch: "+event.getAction());
        if (event.getAction()==MotionEvent.ACTION_DOWN){
          lastx=x;
          lastY=y;
        }else if (event.getAction()==MotionEvent.ACTION_MOVE){
          double dx=x-lastx;
          double dy=y-lastY;
          Log.d(TAG, "onTouch: dx=="+dx+",dy=="+dy);
//      startAnimation(dx,dy);

          // moveMethod1(dx, dy);
          moveMethod2(dx, dy);

          lastx=x;
          lastY=y;
        }
        return true;
      }
    });
  }

//  @Override
//  public boolean onTouchEvent(MotionEvent event) {
//    double x=event.getRawX();
//    double y=event.getRawY();
//    Log.d(TAG, "onTouch: "+event.getAction());
//    if (event.getAction()==MotionEvent.ACTION_DOWN){
//      lastx=x;
//      lastY=y;
//    }else if (event.getAction()==MotionEvent.ACTION_MOVE){
//      double dx=x-lastx;
//      double dy=y-lastY;
//      Log.d(TAG, "onTouch: dx=="+dx+",dy=="+dy);
////      startAnimation(dx,dy);
//
//     // moveMethod1(dx, dy);
//      moveMethod2(dx, dy);
//
//      lastx=x;
//      lastY=y;
//    }
//    return true;
//  }

  //根据属性动画的原理
  private void moveMethod2(double dx, double dy) {
    
    mTv1.setTranslationX((float) (mTv1.getTranslationX()+dx));
    mTv1.setTranslationY((float) (mTv1.getTranslationY()+dy));
  }
  
  //根据margin 原理
  private void moveMethod1(double dx, double dy) {
    ViewGroup.MarginLayoutParams marginLayoutParams= (ViewGroup.MarginLayoutParams) mTv1.getLayoutParams();
    marginLayoutParams.leftMargin+=dx;
    marginLayoutParams.topMargin+=dy;
    mTv1.setLayoutParams(marginLayoutParams);
  }

  private void startAnimation(double dx, double dy) {
    ObjectAnimator objectAnimator=ObjectAnimator.ofFloat(mTv1,"translationX", (float) (mTv1.getTranslationX()+dx)).setDuration(3000);
    objectAnimator.start();

    ObjectAnimator objectAnimator2=ObjectAnimator.ofFloat(mTv1,"translationY", (float) (mTv1.getTranslationY()+dy)).setDuration(3000);
    objectAnimator2.start();
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论