连续向右移动背景并使其从左侧重新出现

Move continously a background to the right and make it reappear from the left

我有一张布局背景图片。我希望它开始向右移动,并且从右侧消失的每一帧都应该重新出现在左侧。因此,图像将只用一帧照片连续移动。我该怎么做?

更新了代码:

 img = (ImageView) findViewById(R.id.imageView1);
 TranslateAnimation animation = new TranslateAnimation(-95.0f, 740.0f,
            0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
 animation.setDuration(5000); // animation duration
 animation.setRepeatCount(5); // animation repeat count

 img.startAnimation(animation); // start animation

最简单和最快的方法是在 ViewGroup 中添加两个 ImageView 并使用两种不同的动画对它们进行动画处理。通过获取容器的宽度,第一个将从其位置 (START) 移动到右边缘 (PARENT_WIDTH),第二个将从容器外部 (-PARENT_WIDTH) 移动到内部(START)。最后,让动画重复 INFINITE 会产生真实循环的错觉。

private ViewGroup parent;
private ImageView imgInner, imgOutter;

@Override
public void onCreate(...) {
    ...
    parent = (ViewGroup) findViewById(R.id.parent_loop);
    imgInner = (ImageView) findViewById(R.id.image_loop_inner);
    imgOutter = (ImageView) findViewById(R.id.image_loop_outter);
    ...
    setImageLoop();
}

private void setImageLoop() {
    // Need a thread to get the real size or the parent
    // container, after the UI is displayed
    imgInner.post(new Runnable() {
        @Override
        public void run() {
            TranslateAnimation outAnim =
                    new TranslateAnimation(
                            0f, parent.getWidth(), 0f, 0f);
                    // move from 0 (START) to width (PARENT_SIZE)
            outAnim.setInterpolator(new LinearInterpolator());
            outAnim.setRepeatMode(Animation.INFINITE); // repeat the animation
            outAnim.setRepeatCount(Animation.INFINITE);
            outAnim.setDuration(2000);

            TranslateAnimation inAnim =
                    new TranslateAnimation(
                            - parent.getWidth(), 0f, 0f, 0f);
                    // move from out width (-PARENT_SIZE) to 0 (START)
            inAnim.setInterpolator(new LinearInterpolator());
            inAnim.setRepeatMode(Animation.INFINITE);
            inAnim.setRepeatCount(Animation.INFINITE);
            inAnim.setDuration(2000); // same duration as the first

            imgInner.startAnimation(outAnim); // start first anim
            imgOutter.startAnimation(inAnim); // start second anim
        }
    });
}

容器 ViewGroup 的宽度为 match_parent,但它可以更改,因此 START 属性将被类似 parent.getLeft() 的内容替换。此布局可以是 LinearLayoutRelativeLayout 或其他任何布局。例如,我使用了这个:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    ...>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        .../>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        .../>
</FrameLayout>

这给出了我的输出(请记住 gif 使它看起来很不稳定,但实际上并不如此):