我知道你只能從UI線程更改tTxtViews中的文本,但我似乎找不到一種方法來處理這個問題。從線程更改TextView文本
我會介紹一些細節:我試圖讓TextView顯示時間已過,但我無法在一個線程或一個不斷調用的方法中執行此操作。 你能幫助我做到這一點嗎?因爲我幾乎沒有想法。
謝謝。
我知道你只能從UI線程更改tTxtViews中的文本,但我似乎找不到一種方法來處理這個問題。從線程更改TextView文本
我會介紹一些細節:我試圖讓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);
}
非常感謝你! amaxing解決方案! – Yuval3210
使用此
new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do what you want.
}
});
}
}).start();
或使用Handler
:
Runnable r = new Runnable() {
@Override
public void run() {
// Do what you want.
}
};
Handler mHandler = new Handler();
mHandler.post(r);
那麼,如果你知道你不能做到這一點,你一定是試過的東西嗎?在這裏發佈你的試驗,也許我們可以幫助你找出你出錯的地方。 –
A-C說什麼,它取決於你想從哪裏改變TextView。 – Christine