首页 > 代码库 > Android用属性动画拖动view到任意位置
Android用属性动画拖动view到任意位置
直接上图:
代码:
package me.waye; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; public class MoveImgActivity extends Activity { ImageView iv; private int containerWidth; private int containerHeight; float lastX, lastY; RelativeLayout rl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_move_img); rl = (RelativeLayout) findViewById(R.id.rl); iv = (ImageView) findViewById(R.id.iv); iv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: lastX = event.getRawX(); lastY = event.getRawY(); return true; case MotionEvent.ACTION_MOVE: // 不要直接用getX和getY,这两个获取的数据已经是经过处理的,容易出现图片抖动的情况 float distanceX = lastX - event.getRawX(); float distanceY = lastY - event.getRawY(); float nextY = iv.getY() - distanceY; float nextX = iv.getX() - distanceX; // 不能移出屏幕 if (nextY < 0) { nextY = 0; } else if (nextY > containerHeight - iv.getHeight()) { nextY = containerHeight - iv.getHeight(); } if (nextX < 0) nextX = 0; else if (nextX > containerWidth - iv.getWidth()) nextX = containerWidth - iv.getWidth(); // 属性动画移动 ObjectAnimator y = ObjectAnimator.ofFloat(iv, "y", iv.getY(), nextY); ObjectAnimator x = ObjectAnimator.ofFloat(iv, "x", iv.getX(), nextX); AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(x, y); animatorSet.setDuration(0); animatorSet.start(); lastX = event.getRawX(); lastY = event.getRawY(); } return false; } }); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); // 这里来获取容器的宽和高 if (hasFocus) { containerHeight = rl.getHeight(); containerWidth = rl.getWidth(); } } }
activity_move_img.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.android.interactivechart.MoveImgActivity"> <ImageView android:id="@+id/iv" android:src="http://www.mamicode.com/@drawable/b1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
Android用属性动画拖动view到任意位置
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。