我知道您只能从 UI 线程更改 tTxtViews 中的文本,但我似乎找不到处理它的方法。
我将详细介绍一些细节:我正在尝试使用一个 TextView 来显示耗时,但我无法在线程或不断调用的方法中执行此操作。 你能帮我解决这个问题吗?因为我几乎没有想法。
谢谢。
最佳答案
public class MainActivity extends Activity {
protected static final long TIMER_DELAY = 100;
private TextView tv;
protected Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.helloWorld);
handler = new Handler();
handler.post(timerTask);
}
private Runnable timerTask = new Runnable() {
public void run() {
Calendar now = Calendar.getInstance();
//format date time
tv.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND)));
//run again with delay
handler.postDelayed(timerTask, TIMER_DELAY);
}
};
}
我忘了添加这个,抱歉。不要忘记这样做:
@Override
public void onPause() {
if (handler != null)
handler.removeCallbacks(timerTask);
super.onPause();
}
如果你想要简历应用,试试这个
@Override
public void onResume() {
super.onResume();
if (handler != null)
handler.post(timerTask);
}
关于android - 从线程更改 TextView 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13897193/