更正android进度条微调器实现

时间:2014-02-05 10:09:26

标签: android progress-bar

以下是资源文件(activity_main.xml)的相关部分的剪辑:

 <Button android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_get"
    android:onClick="getData" />

<ProgressBar
  android:id="@+id/pbar"
  style="?android:attr/progressBarStyleLarge"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:indeterminate="true" />

以下是来自MainActivity.java的剪辑:

public class MainActivity extends Activity {

    ...

private ProgressBar spinner;

    ...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

...

spinner = (ProgressBar) findViewById(R.id.pbar);
spinner.setVisibility(View.INVISIBLE);

    ...
}

protected void getData(View view) {

    ...

    spinner.setVisibility(View.VISIBLE);

    // Do some task here

    spinner.setVisibility(View.INVISIBLE);

    ...

}

单击按钮后,不显示进度条。但是,根据我阅读的一些文档,有必要在线程中启动进度条而不是上面的方式。如何为上述设计完成进度条的线程实现

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方式,而不是直接在小部件中使用进度条。

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case 0:
        ProgressDialog ProgressDialog = new ProgressDialog(this);
        ProgressDialog
                .setMessage("Please wait...");
        ProgressDialog.setIndeterminate(false);
        ProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        ProgressDialog.show();
        ProgressDialog.setCanceledOnTouchOutside(false);
        ProgressDialog.setCancelable(false);
        return ProgressDialog;
    default:
        return null;
    }
}
 /**
 * Background Async Task 
 * */
class IsContinue extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(0);

    }

    /**
     * Background task
     */
    @Override
    protected String doInBackground(String... params) {
// Do something here
 }
 /**
     * After executing background task
     */
    protected void onPostExecute(String Value) {
 dismissDialog(0);
}

}