80,337
社区成员
发帖
与我相关
我的任务
分享
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;
}
});
}
}