使用uithread更改TextView值

时间:2015-08-26 13:51:18

标签: android textview ui-thread

我试图更改一些textview值,但是当它没有出现在屏幕上时,值不会改变,或者当它出现在屏幕上时它会改变,当向下滚动时并向上滚动它的值返回到旧的我尝试了以下两种方式,但不是它们正在工作:

final Timer timer=new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                myTextView.setText("sometext");
                timer.cancel();
            }
        });
    }
}, 5000, 1000);

MainActivity.this.r1.post(new Runnable() {
    public void run() {
        myTextView.setText("sometext");
    }
});

2 个答案:

答案 0 :(得分:0)

尝试使用Handler

    private void TestThread() {
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
                 handler.post(new Runnable(){
                    public void run() {
                       tvTime.setText("SomeText");
                    }
                 });
        }
    }
    };
    new Thread(runnable).start();
}

您也可以查看AsyncTask DocumentationonPostExecute()将文字设置为TextView

答案 1 :(得分:0)

您必须确保在更改TextView的值之前首先绘制UI,可以通过添加布局侦听器来完成,

ViewTreeObserver vto = getWindow().getDecorView().getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Overrid
public void onGlobalLayout() {
final Timer timer=new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                myTextView.setText("sometext");
                timer.cancel();
            }
        });
    }
}, 5000, 1000);
}
}