我想制作一个动画,每3秒后图像会从上到下连续移动。我使用以下代码
实现了这一目标我的XML文件
<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>
我的活动课
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);
}
}
上面的代码工作正常,但动画不一致。例如,当我在图像移动时触摸屏幕时,动画的平滑性会受到干扰并且变得粗糙。
有没有更好的方法来实现这个目标?
答案 0 :(得分:0)
每3秒后无需添加新的图像视图。您可以设置repeatcount -1(INFINITE)。
public class MainActivity extends Activity {
private TranslateAnimation moveDownwards;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveDownwards = new TranslateAnimation(0, 0, -100, 1000);
moveDownwards.setDuration(3000);
moveDownwards.setFillAfter(true);
moveDownwards.setRepeatCount(-1);
findViewById(R.id.image).startAnimation(moveDownwards);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start|top"
android:background="#ffffff" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</RelativeLayout>