将 View动态改变后的位置 设置为 初始位置
利用缓存来存,读取动态改变后的X,Y
setX()和setY()来设置初始位置。
效果
代码:
import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import static java.lang.String.valueOf; public class DragView1 extends View { private int lastX; private int lastY; private SharedPreferences.Editor editor; public DragView1(Context context) { super(context); initView(); } public DragView1(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public DragView1(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } //初始化,重点1在这里 @SuppressLint("CommitPrefEdits") private void initView() { setBackgroundColor(Color.BLUE); //读取缓存的X,Y SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext()); editor = preferences.edit(); float x= preferences.getFloat("X", 0); float y= preferences.getFloat("Y", 0); Log.e("提取X坐标", valueOf(x)); //设置自定义View的X,Y setX(x); setY(y); } //触控事件处理 @Override public boolean onTouchEvent(MotionEvent event) { // 视图坐标系方式获取坐标 int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { //单点触摸按下事件 case MotionEvent.ACTION_DOWN: // 记录触摸点坐标 lastX = x; lastY = y; break; //单点触摸移动事件 case MotionEvent.ACTION_MOVE: // 计算偏移量 int offsetX = x - lastX; int offsetY = y - lastY; // 在当前left、top、right、bottom的基础上加上偏移量 // layout(getLeft() + offsetX, // getTop() + offsetY, // getRight() + offsetX, // getBottom() + offsetY); offsetLeftAndRight(offsetX); offsetTopAndBottom(offsetY); break; //重点2在这里,单点触摸离开事件 case MotionEvent.ACTION_UP: //将View的X,Y存缓存 editor.putFloat("X", getX()); editor.putFloat("Y", getY()); Log.e("保存X坐标", valueOf(getX())); editor.apply(); break; } return true; } }