android自动显示时间,关于android:如何在随机时间后自动显示图像

这篇博客探讨了如何在Android应用中实现图像在随机时间间隔后逐个显示的功能。作者分享了当前代码的问题,即图像每隔10秒连续显示,而非按随机时间间隔显示。提出了使用Random类生成随机延迟时间,并在Handler中应用该延迟来更新图像。然而,作者遇到了黑屏问题。博客还提到了使用AnimationDrawable和设置不同时间间隔的尝试,但并未解决黑屏问题。解决方案可能涉及更深入的错误排查和代码调整。

我构建了一个Android应用程序,我希望在随机时间后逐个显示图像。

手段

图1显示

10秒后

图2显示

30秒后

图3显示

50秒后

图4显示

我有显示图像的代码但它每隔10秒连续显示图像,而我想在随机时间后显示图像。

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文件是 -

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

android:id="@+id/imageView1"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

我们还可以使用模块化算术概念来重复图像。

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);

设置最小和最大间隔:

static final float MIN_INTERVAL = 10000;

static final float MAX_INTERVAL = 20000;

然后是间隔:

handler.postDelayed(this, Math.rand()*(MAX_INTERVAL-MIN_INTERVAL) + MIN_INTERVAL);

先生,我试过,但是当我运行应用程序时,显示黑屏,没有显示图像。

所以第一张图片显示很好,但是当它第一次改变时,它只会变成黑色?

尝试如下:

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();

如果您希望图像之间有一段随机的时间,则需要使用随机数生成器。 例如:

Random r = new Random();

int timer = r.nextInt(60000-30000) + 30000;

然后你可以在你的run函数中使用handler.postDelayed(this, timer);,并且只要你想要生成一个新的随机数,只需再次调用r.nextInt。

有关随机数的更多信息,请参见:如何在Android中生成特定范围内的随机数?

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值