当前位置:主页 > 移动开发 > Android代码 >

Android控件拖动实例详解

时间:2021-07-12 13:28:24 | 栏目:Android代码 | 点击:

Android控件拖动

Android控件的拖动,主要是通过设置控件的setOnTouchListener()方法,重写它的onTouch()方法。然后通过MotionEvent的不同事件,进行判断,主要是在MotionEvent.ACTION_MOVE中不断重绘控件在画布中的位置,而实现拖动的效果。

public class DragViewActivity extends AppCompatActivity { 
  private Button btn_drag; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_drag_view); 
 
 
    // 获取屏幕的宽高 
    DisplayMetrics dm = getResources().getDisplayMetrics(); 
    final int screenWith = dm.widthPixels; 
    final int screenHeight = dm.heightPixels; 
 
    btn_drag = (Button) findViewById(R.id.btn_drag); 
    btn_drag.setOnTouchListener(new View.OnTouchListener() { 
        int lastX; 
        int lastY; 
        boolean isDraging = false; 
 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
        int ee = event.getAction(); 
        switch (ee){ 
          case MotionEvent.ACTION_DOWN: 
            isDraging = true; 
            lastX = (int) event.getRawX(); 
            lastY = (int) event.getRawY(); 
            break; 
          case MotionEvent.ACTION_MOVE: 
            if (isDraging){ 
              // x轴方向的位移差 
              int dx = (int) event.getRawX() - lastX; 
              // y轴方向的位移差 
              int dy = (int) event.getRawY() - lastY; 
 
              int l = v.getLeft() + dx; 
              int t = v.getTop() + dy; 
              int r = v.getRight() + dx; 
              int b = v.getBottom() + dy; 
 
              // 判断超出屏幕 
              if (l < 0){ 
                l = 0; 
                r = l + v.getWidth(); 
              } 
              if (t < 0){ 
                t = 0; 
                b = t + v.getHeight(); 
              } 
              if (r > screenWith){ 
                r = screenWith; 
                l = r - v.getWidth(); 
              } 
              if (b > screenHeight){ 
                b = screenHeight; 
                t = b - v.getHeight(); 
              } 
 
              // 重绘view 
              v.layout(l, t, r, b); 
              v.postInvalidate(); 
 
              lastX = (int) event.getRawX(); 
              lastY = (int) event.getRawY(); 
            } 
            break; 
 
          case MotionEvent.ACTION_UP: 
            isDraging = false; 
            break; 
          default: 
            break; 
        } 
        return false; 
      } 
    }); 
  } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:

相关文章