动态移动ImageView的位置
我有个一个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;
}
});
}
}
...全文
相关推荐
imageView 放大 居中 左右移动
imageView 放大 居中 左右移动
Android RelativeLayout任意位置添加ImageView
最近要实现橡皮擦功能 当手指按下时 出现图片,手指移动的过程中,图片随着移动的需求,这样就需要在RelativeLayout中动态添加图片,然后OnTouchEvent事件中,来处理移动事件 具体代码如下: 1.动态添加ImageView; 布局文件: private RelativeLayout main_area; main_area=(RelativeLayout)findViewById(R.id.main_area); 2.添加Imagview private void addEraserI
安卓ImageView水平方向上随着手指来回移动
安卓ImageView水平方向上随着手指来回移动
基于Android实现随手指移动的ImageView
主要介绍了基于Android实现随手指移动的ImageView的相关资料,需要的朋友可以参考下
MovingImageView自己移动的imageview.rar
MovingImageView自己移动的imageview.rar,太多无法一一验证是否可用,程序如果跑不起来需要自调,部分代码功能进行参考学习。


