0

ループを繰り返すたびに GUI を更新しようとしています。同様の質問に対する他の回答を読みましたが、まだ機能しません。以下のコードでは、simulate を呼び出します。これは、必要に応じて GUI コンポーネントを計算および変更するループ呼び出しステップを実行しますが、ループが完全に終了するまで GUI は更新されません。各反復後に更新するにはどうすればよいですか?

public void step(View v) {
    for (int i = 0; i < cells.length; i++)
        update(i);

    count++;

    Toast.makeText(getApplicationContext(), count + "", 1000).show();
}

public void simulate(View v) {
    while (!pause) {
        step(v);

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void update(final int i)
{
            //This goes through each button and counts the neighbors (this is the 
            //intensive work
    int neighbors = getNeighbors(i);

            //With the information provided from the getNeighbors the following if
            //statement updates the GUI using the dead and alive method calls.
    if (isAlive(cells[i])) {
        if (neighbors < 2)
            dead(cells[i]);
        else if (neighbors > 3)
            dead(cells[i]);
    } 
    else {
        if (neighbors == 3)
            alive(cells[i]);
    }
}
4

3 に答える 3

1

問題は、そのコードをアプリケーションのメイン スレッドで実行していることです。GUI は同じスレッドで実行され、ブロックしている間は更新できません。

別のタスクで計算を実行してから、メイン プロセスにメッセージを送信して GUI を更新する必要があります。背景情報については、これをお読みください (これに慣れていない場合は、最初に背景をお読みください)。

http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

これを行う最も簡単な方法は、AsyncTask を使用してから、"onProgressUpdate()" で GUI の更新を行うことです。AsyncTask を使用すると作業は簡単になりますが、AsyncTask の実行中に基になるアクティビティが破棄される可能性があることに注意する必要があります。これはドキュメントではあまり詳しく説明されていませんが、Fragments を使用することがおそらく最善の対処方法であることがわかりました。非常に優れた説明については、この記事を読んでください。

http://blogactivity.wordpress.com/2011/09/01/proper-use-of-asynctask/

注意: AsyncTask のドキュメントもお読みください。フォーラムの制限により、リンクを投稿できませんでした。

于 2012-06-21T16:45:36.250 に答える
0

UI 作業は UI スレッドで、非 UI 作業は非 UI スレッドで行うべきであると常にアドバイスされていますが、HoneyComb android バージョンからは LAW になりました。When we start an application in Android, it start on the Dedicated UI thread, creating any other thread will drop you off the UI thread, you normally do this to do some process intensive work, but when you want to display the output of the non-ui thread process, on the ui thread then you will experience lagging, exception etc...

私の見解では、これはいくつかのtwo方法で行うことができます....

  1. Handlerの使用... Handler stores the reference of the thread on which it was created, Initialize Handler inside the onCreate() method, and then use handler.post() to update the UI thread.

  2. Android が提供するAsyncTask<>を使用すると、UI スレッドと非 UI スレッドが同期されます

    AsyncTask<> のメソッド

    doInBackground(String...) // Work on the Non-UI thread

    postExecute(String result) // Getting the Output from the Non-Ui thread and

    Putting the Output back on the UI Thread

于 2012-06-21T17:23:09.513 に答える
0

これには AsyncTask を使用する必要があると思います。

ドキュメントを読んでみてください..

http://developer.android.com/reference/android/os/AsyncTask.html

于 2012-06-21T15:54:43.610 に答える