2013-04-28 39 views
0

點擊一個按鈕我想顯示一個吐司消息,雖然有一些工作正在進行,但即使通過我有它在開始時吐司沒有被顯示,直到結束敬酒沒有在正確的時間顯示

if (id == R.id.edit_score_button_update) { 

Toast.makeText(this, "Updating please wait", Toast.LENGTH_LONG).show(); 

//Some code that update database 

finish(); 

什麼是強制烤麪包首先被顯示的最佳方式。感謝您的時間

+4

您可以執行阻斷UI線程操作(例執行netwok操作等),所以麪包不會顯示出來utill UI線程可以自由 – Pragnani 2013-04-28 15:32:25

+0

嘗試使用的AsyncTask爲您的網絡操作或數據庫更新,並在onPreExecute()' – Houcine 2013-04-28 15:45:40

+0

中顯示你的Toast會不會有一個while循環有這種效果? – 2013-04-28 15:55:05

回答

1

您需要在活動類中創建一個擴展AsyncTask的類。

UpdateDBTask task = new UpdateDBTask(); 
task.execute(someString); 

在你的異步任務可以定義3個變量 - (所有這些都不可能是原始:意int例如必須是Integer)。

首先是您發送給異步任務對象以在doInBackground()中使用的內容。 其次是你用來更新你的主線程onProgressUpdate()。 三是doInBackground()返回,將得到並用於顯示結果(再次 - 在主線程中)。你不必使用其中的任何一個(在我給你的代碼中使用LIKE),但是在擴展AsyncTask時必須寫入類型。

public class UpdateDBTask extends AsyncTask<String, Integer, String> { 

    @Override 
    protected void onPreExecute() { 
     //Everything written here will happen in main thread before doInBackground() starts. 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     //Do your things in different thread, allowing the main 
     //thread change things on GUI (Like showing toast...) 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
    //Everything you do here happens in the main thread AFTER doInBackground() is done. 
    } 
} 
+0

謝謝。它做到了。現在更好的工作並不需要敬酒,而是在後臺完成 – 2013-05-08 13:47:38