Android - 如何使用3个ImageView切换视图?

时间:2010-02-25 21:26:24

标签: java android multithreading

我需要帮助提出一种在Android中使用某种类型的视图或布局组合执行以下序列的方法:

我有3个图像对象...说对象A,B和C ...

[所有物体不可见和分层,一个在另一个之上...... A / B / C,如在RelativeLayout中] - > [淡入对象A] - > [显示A为200ms] - > [同时淡出对象A并淡入对象B] - > [显示对象B为200ms] - > [同时淡出对象B并淡入对象C] - > [对象C无限期地留在屏幕上]

我已经尝试了Threads,AsyncTasks,Handlers,自定义布局,AnimationListeners等的所有组合,但我尝试过的所有内容都失败了。

如果只有ViewSwitcher可以拍摄2个以上的视图......请帮助。

赖安

2 个答案:

答案 0 :(得分:1)

线程的主要内容是它们应该允许你执行并行任务,但问题是它们不能保证这些任务在执行时实际看起来“多么平行”。由于调度程序决定在任何给定时间执行哪个线程,因此无法保证图像将被正确淡入/淡出。虽然您可以使用多线程代码执行此任务,但我认为它不是一个好的候选者。

最好的办法是在动画的每一帧上更新两个图像(淡入/淡出)。当A开始淡出时B发出信号,然后它会开始淡入。AB会得到平滑过渡每个帧都更新,你不会有线程的任何不确定性。对BC执行相同的操作。

更新:你抓住了我! :)
我以为你让我只是给你一般的信息,但现在你让我走投无路,我别无选择,只能谷歌的东西:)。好的,所以android库有一些animation classes,该库还为您提供了一种实际执行frame-by-frame animation的方法。

我会给你一个简单的黑客攻击,但我确信有更好的方法可以做到这一点: 动画会拍摄一些应在一定时间内显示的图像,因此您只需要交替拍摄图像。

<!-- Animation frames are AfadeOut01.png to AfadeOut03.png and BfadeIn01.png to BfadeIn03.png files inside the res/drawable/ folder,  -->
 <animation-list android:id="selected" android:oneshot="true">
    <item android:drawable="@drawable/AfadeOut01" android:duration="50" />
    <item android:drawable="@drawable/BfadeIn01" android:duration="50" />
    <item android:drawable="@drawable/AfadeOut02" android:duration="50" />
    <item android:drawable="@drawable/BfadeIn02" android:duration="50" />
    <item android:drawable="@drawable/AfadeOut03" android:duration="50" />
    <item android:drawable="@drawable/BfadeIn03" android:duration="50" />
 </animation-list>

您必须加载xml动画并显示动画,执行以下操作:

 // Load the ImageView that will host the animation and
 // set its background to our AnimationDrawable XML resource.
 ImageView img = (ImageView)findViewById(/*resourceImageID e.g. AfadeOut03*/);
 img.setBackgroundResource(/*backgroundResource*/);

 // note that this loads the resource from an XML file, but
 // instead of getting the resource from file you can generate
 // it from a single image by performing the required modifications
 // of the image and storing them in a resource.

 // Get the background, which has been compiled to an AnimationDrawable object.
 AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

 // Start the animation
 frameAnimation.setOneShot(true);// don't loop if not set in XML
 frameAnimation.start();

好的,所以我知道这是一个肮脏的黑客,但它应该做你想要的:)。如果这对你来说过于简单和不酷,那么你可以走原路线并试图找出如何逐帧显示图像等。

答案 1 :(得分:0)

这些东西并不真正需要线程,它们需要动画。更具体地说是AlphaAnimation。查看Alpha Animation页面,了解有关如何使用它的详细信息。这很简单,你只需设置你想要发生的事情以及你想要多长时间。