动态移动ImageView的位置

Marco_lhc Marco_lhc 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我有个一个ImageView不断播放动画,现在能实现用TranslationAnimation实现ImageView的移动效果。但是拖完以后ImageView又回到原来的位置。我希望我鼠标拖动到哪ImageView就在哪个位置。这该如何实现。试了setPadding,setMargins都不奏效。
package com.example.animationdrawable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {
private ImageView imgView;
private float curX=0;
private float curY=0;
float nextX=0;
float nextY=0;
int width;
int height;//屏幕的高度
boolean isstart=false;
RelativeLayout.LayoutParams params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics dm=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
width=dm.widthPixels;
height=dm.heightPixels;
imgView=(ImageView)findViewById(R.id.anim);

curX=(width-60)/2;
curY=height-60*2;


final AnimationDrawable animation=(AnimationDrawable)imgView.getBackground();
final Handler handler =new Handler(){
public void handleMessage(Message msg){

if(msg.what==0x123){
float moveX=nextX-curX;
float moveY=nextY-curY;


TranslateAnimation anim=new TranslateAnimation(curX,nextX-imgView.getWidth()/2,curY,nextY-imgView.getHeight()/2);
curX=nextX;
curY=nextY;
anim.setDuration(200);
imgView.startAnimation(anim);

}
if(msg.what==0x111){
params=(RelativeLayout.LayoutParams)imgView.getLayoutParams();
params.setMargins(Math.round(nextX), Math.round(nextY)
, Math.round(width-60-nextX), Math.round(height-60-nextY));
}
}
};

imgView.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(!isstart)
animation.start();
switch(event.getActionMasked()){
case MotionEvent.ACTION_MOVE:
nextX=event.getX();//获得当前的X坐标
nextY=event.getY();//获得当前的Y坐标
handler.sendEmptyMessageDelayed(0x123, 200);
break;
case MotionEvent.ACTION_UP:
handler.sendEmptyMessage(0x111);
break;
}
return true;
}
});

}

}
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
Marco_lhc
Android 80,490 成员 91,375 内容