android属性动画移除屏幕外,Android用属性动画拖动view到任意位置

本文通过一个实例展示了如何在Android应用中使用属性动画实现拖动ImageView到屏幕任意位置的功能。代码中设置了OnTouchListener监听触摸事件,根据ACTION_DOWN和ACTION_MOVE事件更新View的位置,并防止其移出屏幕。同时,使用ObjectAnimator平滑地移动View的x和y坐标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上图:

代码:

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 

nextY = 0;

} else if (nextY > containerHeight - iv.getHeight()) {

nextY = containerHeight - iv.getHeight();

}

if (nextX 

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

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">

android:id="@+id/iv"

android:src="@drawable/b1"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值