2013-07-12 14 views
0

我正在學習如何使用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,這不是我正在尋找的問題)。

+0

首先,嘗試做'onResume()'而不是'onStart()'做。這個ew活動完全隱藏了舊的活動,並且這個活動完全隱藏了,onStart()可能不叫 '@Override public void onResume(){ super.onResume(); isUiVisible = true; new UpdateUi()。execute(); }' –

+0

不幸的是,它並沒有解決我的問題。但類型a1pha的答案解決了這個問題。謝謝你的幫助。 – luch0043

回答

0

TextView沒有顯示出來,可能是因爲它裏面沒有任何文本......如果不查看layout.xml文件,肯定無法確定。

您得到該行爲是因爲變量isUiVisible僅在調用onPause()時變爲false,即您切換活動時。在那一刻,AsyncTask退出他的doInBackground方法並執行onPostExecute,它使TextView中出現一些文字。

要嘗試修復你的代碼,你應該調用publihProgress()doInBackground然後用onProgressUpdate在UIThread更新您的TextView

+0

您的建議有效,正是我所期待的。非常感謝你的解釋,它幫助我更好地理解行爲。 :) – luch0043