簡體   English   中英

進度對話框不會出現

[英]Progressdialog won't show up

我想顯示此對話框,而線程嘗試建立連接,但是當我按下啟動此方法的按鈕時,該對話框不會顯示。

public void add_mpd(View view) {
    dialog = ProgressDialog.show(MainActivity.this, "", "Trying to connect...");
    new Thread(new Runnable() {
        public void run() {
            try {
                String child;
                EditText new_mpd = (EditText) findViewById(R.id.new_mpd);
                child = new_mpd.getText().toString();
                mpd = new MPD(child);
                children.get(1).add(child);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (MPDConnectionException e) {
                e.printStackTrace();
            }
        }
    }
    ).start();
    adapter.notifyDataSetChanged();
    dialog.dismiss();
}

它不會出現,因為(阻塞)工作是在另一個線程中完成的。 這意味着, Thread類的start()方法不會阻塞。

因此,您顯示對話框,線程啟動,對話框立即關閉(因此關閉)。

在你的run()方法結束時調用dismiss() ,它應該可以正常工作。


以上可能對您有用,但您不應該直接使用Thread類。 它周圍有包裝器,使用起來更舒適。

在 Android 中,如果你想在 UI-Thread 之外做長期的工作,你應該使用AsyncTask

此外,為了建立在 Lukas 所說的基礎上,您可以查看此示例。

http://www.helloandroid.com/tutorials/using-threads-and-progressdialog

public class ProgressDialogExample extends Activity implements Runnable {

    private String pi_string;
    private TextView tv;
    private ProgressDialog pd;

    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);

            tv = (TextView) this.findViewById(R.id.main);
            tv.setText("Press any key to start calculation");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

            pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
                            false);

            Thread thread = new Thread(this);
            thread.start();

            return super.onKeyDown(keyCode, event);
    }

    public void run() {
            pi_string = Pi.computePi(800).toString();
            handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                    pd.dismiss();
                    tv.setText(pi_string);

            }
    };

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM