我正在學習如何使用asyncTask,並試圖實時顯示TextView。 mainActivity有幾個按鈕可以啓動新的活動,並附帶一個顯示每200毫秒更改值的TextView。但問題是,直到我點擊按鈕啓動另一個活動時,TextView才顯示出來,並且當按「返回按鈕」返回到mainActivity時,該值不會改變。但是,當我按下按鈕開始另一個活動時,它會更改該值。使用asyncTask實時顯示TextView的問題
private TextView t;
private int counter;
private boolean isUiVisible = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.counter);
counter = 0;
}
@Override
public void onStart(){
super.onStart();
isUiVisible = true;
new UpdateUi().execute();
}
@Override
public void onPause(){
super.onPause();
isUiVisible = false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class UpdateUi extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
while (true) {
if (isUiVisible) {
counter++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// Ensure the asynkTask ends when the activity ends
break;
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
t.setText(counter + "");
}
}
public void callRed(View view){
Intent intent = new Intent(this, RedActivity.class);
startActivity(intent);
}
public void callYellow(View view){
Intent intent = new Intent(this, YellowActivity.class);
startActivity(intent);
}
我已經在onProgressUpdate中嘗試setText,但它什麼都沒顯示。我也搜索瞭解其他是否存在問題,但似乎它們與我的問題一樣(一個是onClickListener,這不是我正在尋找的問題)。
首先,嘗試做'onResume()'而不是'onStart()'做。這個ew活動完全隱藏了舊的活動,並且這個活動完全隱藏了,onStart()可能不叫 '@Override public void onResume(){ super.onResume(); isUiVisible = true; new UpdateUi()。execute(); }' –
不幸的是,它並沒有解決我的問題。但類型a1pha的答案解決了這個問題。謝謝你的幫助。 – luch0043