延迟使用“处理程序”在Android For Loop中不起作用

问题描述

我有一个带有一些值的HashMap对象。我想在3秒后遍历这些值,并在textView上显示每个值。我正在使用Handler进行延迟。这是我的代码

handler = new Handler();

for (String i: myHashmap.values()){
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            textView.setText(null);
            textView.setText(i);
        }
    },3000);
}

问题是上述代码仅一次更改了该值。之后,文本视图将停留在Hashmap的第一个值上。

解决方法

尝试一下:

final Handler handler = new Handler();
int count = 0;

final Runnable runnable = new Runnable() {
    public void run() {

        textView.setText(null);
        textView.setText(myHashmap.get(count));
        if (count++ < myHashmap.size()) {
            handler.postDelayed(this,3000);
        }
    }
};

// Call first time
handler.post(runnable);
,

添加索引以乘以延迟并以3秒的间隔更改值

int counter = 1;

for (String i : myHashmap.values()) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            textView.setText(i);
        }
    },3000 * counter);
    counter++;
}
,

尝试一下

int i = 0;

    HashMap<String,String> hashMap = new HashMap<>();
    hashMap.put("Key1","One");
    hashMap.put("Key2","Two");
    hashMap.put("Key3","Three");
    hashMap.put("Key4","Four");
    hashMap.put("Key5","Five");

    Map<String,String> map = new TreeMap<>(hashMap); // Sort HashMap by Key

    textView.post(new Runnable()
    {
        @Override
        public void run()
        {
            List<String> strings = new ArrayList<>(map.values());

            if (i < strings.size())
            {
                textView.setText(strings.get(i));
                i++;
                textView.postDelayed(this,3000);
            }
        }
    });