Android View 跟随手指移动 最简单实现方法

    技术2024-10-28  20

    话不多说,上代码:

    package com.test.movemyview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RelativeLayout rl = new RelativeLayout(this); final ImageView iv = new ImageView(this); iv.setImageResource(R.mipmap.ic_launcher); RelativeLayout.LayoutParams ivlp = new RelativeLayout.LayoutParams(500, 500); ivlp.addRule(RelativeLayout.CENTER_IN_PARENT); ivlp.setMargins(100,10,50,200); iv.setLayoutParams(ivlp); iv.setOnTouchListener(new View.OnTouchListener() { private float downX; private float downY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //按下位置 downX = event.getRawX(); downY = event.getRawY(); break; case MotionEvent.ACTION_MOVE: float moveX = event.getRawX(); float moveY = event.getRawY(); float dx = moveX - downX; float dy = moveY - downY; float tX = v.getTranslationX() + dx; float tY = v.getTranslationY() + dy; v.setTranslationX(tX); v.setTranslationY(tY); // 下一次按下位置 downX = event.getRawX(); downY = event.getRawY(); break; case MotionEvent.ACTION_UP: //复位 // v.setTranslationX(0); // v.setTranslationY(0); break; } return true; } }); rl.addView(iv); setContentView(rl); } }

     

    Processed: 0.013, SQL: 12