簡體   English   中英

如何在 for() 循環中同時將 android 背景顏色設置為多個線性布局?

[英]How to set in android background color to several linearlayouts at time in for() loop?

安卓。 我正在嘗試設置背景顏色以制作某種培訓師。 但是這個循環一次為所有 4 個 LivearLayouts 設置背景顏色 - 在最后一次迭代之后。 我需要一個接一個地完成。 我該怎么做?

    private LinearLayout[] lls;
    lls = new LinearLayout[4];
    lls[0] = findViewById(R.id.ll01);
    lls[1] = findViewById(R.id.ll02);
    lls[2] = findViewById(R.id.ll03);
    lls[3] = findViewById(R.id.ll04);
    public void onClick(View view) throws InterruptedException {
        for (int i = 0; i < 4; i++) {
            Thread.sleep(3000);
            lls[i].setBackgroundColor(Color.parseColor("red"));
        }
    }

這樣的代碼會在第 4 次迭代結束后立即更改所有 4 個對象的顏色。 在此之前,顏色都沒有變化。

我認為您應該使用處理程序而不是 for 循環。 處理程序更便於延遲和做一些事情。 我正在為您放置一些編輯過的代碼。

private LinearLayout[] lls;

private Long timeInMillis = 3000L;

private Handler handler;

private Runnable runnable;

private int index = 0;

private void setColors(){
    lls = new LinearLayout[4];
    lls[0] = findViewById(R.id.ll01);
    lls[1] = findViewById(R.id.ll02);
    lls[2] = findViewById(R.id.ll03);
    lls[3] = findViewById(R.id.ll04);

    handler = new Handler();

    runnable = new Runnable() {
        @Override
        public void run() {
            if(index!=lls.length){
                lls[index++].setBackgroundColor(Color.parseColor("red"));
                handler.postDelayed(runnable,timeInMillis);
            }
        }
    };

    handler.postDelayed(runnable,timeInMillis);

}

這是錯誤的代碼。 您不能在一個線程中更改活動中的 smth。 通過在 MainActivity 中為 BroadcastReciever 發送廣播消息的循環添加線程解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM