I want to do an animation in which an image continuously keeps moving from top to bottom after every 3 seconds. I have achieved this using the following code
My XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top"
android:baselineAligned="false"
android:background="#ffffff">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout1">
</RelativeLayout>
</LinearLayout>
My Activity class
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.util.Timer;
import java.util.TimerTask;
public class GameActivity extends AppCompatActivity {
private RelativeLayout layout1;
private TranslateAnimation moveDownwards;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
layout1 = (RelativeLayout) findViewById(R.id.layout1);
moveDownwards = new TranslateAnimation(0, 0, -100, 1000);
moveDownwards.setDuration(3000);
moveDownwards.setFillAfter(true);
startTimer();
}
@Override
protected void onResume() {
super.onResume();
startTimer();
}
private void startTimer() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
ImageView iv1 = new ImageView(GameActivity.this);
iv1.setImageResource(R.drawable.c_orange);
layout1.addView(iv1);
iv1.startAnimation(moveDownwards);
}
});
}
};
timer.schedule(task,0,3000);
}
}
Above code is working fine but the animation is not consistent. For example, when I touch the screen while the image is moving, the smoothness of animation is disturbed and it becomes rough.
Is there any better way to achieve this???