0

私はこのコードを持っています:

    public void createTask() {

    for (int i = 0; i < 6; i++) {
        Random rnd = new Random();
        int color = rnd.nextInt(10);
        showImage(color);
    }

しかし、画像ビューを循環させたい.. 1つを表示し、3秒間画面に表示してから2番目を表示し、それを3秒間画面に保持し、3番目を表示するなど.

コードをクリーンに保つために showImage および hideImage メソッドを作成しました。

    public void showImage(int color) {
    ((ImageView) findViewById(myImagebtns[color]))
            .setVisibility(View.VISIBLE);
};

UI をロックせずに待機時間 (スリープ? スレッド?) をプログラムするにはどうすればよいですか?

4

1 に答える 1

2

UI スレッドをブロックしないようにするにはHandler、そのpostDelayedメソッドで a を使用します。

int repeatCount = 0;
handler = new Handler();
runnable = new Runnable() {

    @Override
    public void run() {
        switchImage();
            Log.d("MSG", "repeatCount is : " + repeatCount);
            repeatCount ++;
            if(repeatCount < 5) {
                handler.postDelayed(this, 3000);
            }
    }
};

handler.postDelayed(runnable, 3000);

単一の ImageView を使用し、その背景色または画像リソースを 3 秒ごとに切り替えることをお勧めします。(ImageViewすべての画像に s を使用すると、アプリのコストがかかります。)

public void switchImage() {
    ImageView myImageView = (ImageView) findViewById(R.id.myImageView); 
    // TODO: get your image or color here and apply it to your single imageView
    // You may need an index while getting the next image or randomly get it.

    myImageView.setImageResource(getNextImageResId());
}

編集: n 回切り替えたい場合は、変数 (repeatCount など) を定義し、その変数をインクリメントできます。ログアウトすると、次のように表示されます (すべての行に 3 秒の差があることがわかります)。

11-11 20:17:19.909: D/MSG(1068): repeatCount is : 0
11-11 20:17:22.917: D/MSG(1068): repeatCount is : 1
11-11 20:17:25.921: D/MSG(1068): repeatCount is : 2
11-11 20:17:28.921: D/MSG(1068): repeatCount is : 3
11-11 20:17:31.925: D/MSG(1068): repeatCount is : 4
于 2013-11-10T15:02:18.940 に答える