问题
I used following code to move a image it works fine but while moving the image not perform a smooth moving. Can anyone find the problem in my code?
handler = new Handler();
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
if(left<=400){
left=left+1;
RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
rp.setMargins(left, top, 0, 0);
Train.setLayoutParams(rp);
}else{
Toast.makeText(getApplicationContext(), "Toast completed", Toast.LENGTH_SHORT).show();
t.cancel();
}
}
});
}
}, 0,30);
回答1:
TimerTask and Threads are not good choice for consistent UI changes.
Create CustomView by entending SurfaceView .
Manage some class variables for position of views.
In onDraw() create view and update variables for next positioning .
Wherever want to refresh manually, call invalidate.
Follow this tutorial for more help .
回答2:
ImageView img_animation = (ImageView) findViewById(R.id.imageView1);
TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(5000); // animation duration
animation.setRepeatCount(5); // animation repeat count
animation.setRepeatMode(2); // repeat animation (left to right, right to left )
//animation.setFillAfter(true);
img_animation.startAnimation(animation);
Animation is the best smooth moving !! Try it !!
来源:https://stackoverflow.com/questions/8135416/how-can-i-get-a-smooth-move-using-timertask