如何暂停几秒钟

时间:2015-08-04 15:03:30

标签: android

我希望像幻灯片一样显示图像,但在显示下一张图像之前我无法暂停5秒......

我试图让线程休眠,但它暂停了15秒并显示了最后一张(第3张)图像。

for (int i = 0; i < 3; i++) {
    File imgFile = new File(paths[i]);

    if(imgFile.exists()){
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        mimage.setImageBitmap(myBitmap);
    }

    //**I want the thread pause for 5 seconds here**
}

2 个答案:

答案 0 :(得分:1)

你需要一个处理程序

    Handler handler1 = new Handler();
    for(int i=0;i<3;i++) 
    {
        handler1.postDelayed(new Runnable() {

            @Override
            public void run() 
            {
                File imgFile = new  File(paths[i]);

                if(imgFile.exists())
                {

                    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                    mimage.setImageBitmap(myBitmap);
                }
            }
        }, 5000 * i );
    } 

答案 1 :(得分:0)

试试这个:

public class YourClass {
    private String[] paths;
    private int mNextImageIndex = 0;

    public void switch() {


        File imgFile = new  File(paths[mNextImageIndex]);

        if(imgFile.exists()){

            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            mimage.setImageBitmap(myBitmap);
        }

        mNextImageIndex = (mNextImageIndex + 1) % paths.length;

        new Handler().postDelayed(new Runnable() {
            public void run() {
                switch();
            }
        },5000);
    }
}