0

我有一个button. 在onclick事件中,想要运行一个progressDialog,然后在加载progressDialog时运行一个AsyncTask.

我的代码:

方法 OnCreate

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

principal_layout = (RelativeLayout) findViewById(R.id.principal_layout);
text_search = (TextView) findViewById(R.id.textView1);
search_button = (Button) findViewById(R.id.button1);
input_song = (EditText) findViewById(R.id.editText1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);

search_button.setOnClickListener(new OnClickListener() {

@Override
    public void onClick(View v) {

        runOnUiThread(new Runnable() {
                public void run() {
                    pd = ProgressDialog.show(MainActivity.this, "Working..", "Loading, please wait..", true, false);
                }
            });

        handler.sendEmptyMessage(1);

    }});
}

方法处理程序(var Handler)

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        if(msg.what == 1){
            try {
                songs = new AsyncTasks().new GetSong(MainActivity.this).execute("mySong","1").get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            catch (ExecutionException e) {
                e.printStackTrace();
            }
            sendEmptyMessage(0);
        }
        else if(msg.what == 0){
            Toast.makeText(MainActivity.this, "Finished process", Toast.LENGTH_SHORT).show();

            if(pd != null && pd.isShowing()){
                pd.dismiss();
            }
        }
    }

};

该代码不会产生任何错误,但接下来是以下内容:

当我单击按钮时,程序执行以下行:

歌曲 = new AsyncTasks().new GetSong(MainActivity.this).execute("mySong","1").get();

,一旦它完成运行,那么最近会有progressDialog显示。我希望它显示单击按钮的确切时刻(没有延迟)。

4

1 回答 1

0

您可以简单明了地做到这一点:

Handler h = new Handler();
button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        pd = ProgressDialog.show(MainActivity.this, "Working..", "Loading, please wait..", true, false);
        new Thread(new Runnable() {
            public void run() {
                //Loading code
                h.post(new Runnable() {
                    public void run() {
                        pd.dismiss();
                    }
                });
            }
        }).start();
    }
});
于 2013-05-24T04:25:13.693 回答