【发布时间】:2016-12-21 14:11:25
【问题描述】:
我的布局背景有一张图片。我希望它开始向右移动,从右侧消失的每一帧都应该重新出现在左侧。因此,图像将仅以照片的一帧持续移动。我该怎么做?
【问题讨论】:
标签: android android-layout android-animation
我的布局背景有一张图片。我希望它开始向右移动,从右侧消失的每一帧都应该重新出现在左侧。因此,图像将仅以照片的一帧持续移动。我该怎么做?
【问题讨论】:
标签: android android-layout android-animation
最简单、最快捷的方法是在ViewGroup 中添加两个ImageViews,并使用两个不同的动画对它们进行动画处理。通过获取容器的宽度,第一个将从其位置 (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() 之类的东西替换。此布局可以是LinearLayout、RelativeLayout 或其他。例如,我使用了这个:
<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 使它看起来不连贯,而实际上不是):
【讨论】:
更新了代码:
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
【讨论】: