Android 如何在随机时间后自动显示图像
我构建了一个android应用程序,我希望在一个随机时间后一个接一个地显示图像。 意味着 图1显示 10秒后 图2展示 30秒后 图3展示 50秒后 图4展示 我有显示图像的代码,但它每10秒连续显示一次图像,而我希望在随机时间后显示图像Android 如何在随机时间后自动显示图像,android,timer,handler,Android,Timer,Handler,我构建了一个android应用程序,我希望在一个随机时间后一个接一个地显示图像。 意味着 图1显示 10秒后 图2展示 30秒后 图3展示 50秒后 图4展示 我有显示图像的代码,但它每10秒连续显示一次图像,而我希望在随机时间后显示图像 public class MainActivity extends Activity { ImageView imageView; public void onCreate(Bundle savedInstanceState) { supe
public class MainActivity extends Activity {
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
final int []imageArray=
{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 10000); //for interval...
}
};
handler.postDelayed(runnable, 10000); //for initial delay..
}
xml文件是-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
设置最小和最大间隔:
static final float MIN_INTERVAL = 10000;
static final float MAX_INTERVAL = 20000;
那么对于间隔:
handler.postDelayed(this, Math.rand()*(MAX_INTERVAL-MIN_INTERVAL) + MIN_INTERVAL);
如果希望图像之间存在随机时间,则需要使用随机数生成器。例如:
Random r = new Random();
int timer = r.nextInt(60000-30000) + 30000;
然后您可以只使用handler.postDelayed(这个是计时器)
在您的run函数中,任何时候您想要生成一个新的随机数,只需再次调用r.nextInt
有关随机数的更多信息,请点击此处:尝试以下操作:
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.mipmap.download), 1000);
animation.addFrame(getResources().getDrawable(R.mipmap.downloada), 5000);
animation.addFrame(getResources().getDrawable(R.mipmap.ic_launcher), 3000);
animation.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.img);
imageAnim.setBackgroundDrawable(animation);
// start the animation!
animation.start();
我们也可以使用模运算概念来重复图像
int cimi;
int img[] ={R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,R.drawable.f};
// inside onCreate()..
i = (ImageView)findViewById(R.id.iv1);
Runnable runn = new Runnable() {
@Override
public void run() {
i.setImageResource(img[cimi]);
cimi++;
cimi = cimi%img.length;
i.postDelayed(this,2000);
}
};
i.postDelayed(runn,2000);
先生,我试过了,但是当我运行应用程序时,黑屏显示,没有图像显示。所以第一个图像显示的很好,但是当它第一次改变时,它只是变为黑色?