首页 > 解决方案 > Android Ui 未在线程中更新

问题描述

在日志中正常工作,但在 setText 中不会更改屏幕上的任何内容,并且不会发生错误。

//within the onCreate method 
myRef.child(fireUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    millis = Long.valueOf(dataSnapshot.child("millis").getValue().toString());
                    t1.run();
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Intent i = new Intent(getApplicationContext(), SplashActivity.class);
                    startActivity(i);
                    finish();
                }
            });

//Out of the onCreate method
    Thread t1 = new Thread(){
            @Override
            public void run() {
                try {
                    long i;
                    for(i=System.currentTimeMillis(); i < millis+millis_wait; i=System.currentTimeMillis()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                long pr = (millis + millis_wait) - System.currentTimeMillis();
                                tx_time.setText(""+pr);
                                Log.i("TST", "" + pr);
                            }
                        });
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

我应该改变什么?

正如我所说,代码正在运行,正在调用并完美执行 Log 事件,唯一没有发生的是更新 setText 根本没有运行,也没有任何错误。

标签: javaandroid

解决方案


调用t1.start();你的 UI 线程来运行它


推荐阅读