2011-11-11 81 views
0

我在android中有一個不確定進度的問題。我有一個按鈕,點擊按鈕時應該出現不確定的進度條,並且在任務結束時進度條應該消失。android不確定進度條問題

但我無法做到這一點。

package com.indeterminate; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.Window; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.*; 

public class IndeterminateProgressBarActivity extends Activity { 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 

    super.onCreate(savedInstanceState); 
    final ProgressBar pb=new ProgressBar(this); 
    pb.setVisibility(View.GONE); 
    Button b =new Button(this); 
    b.setText("Click to start spinning"); 
    b.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      pb.setVisibility(View.VISIBLE); 
      // Want to write some code 
      pb.setVisibility(View.GONE); 

      // But the progress bar is not shown on the screen 

    LinearLayout l=new LinearLayout(this); 
    l.addView(pb); 
    l.addView(b); 

    this.setContentView(l); 
} 

}

+0

http://stackoverflow.com/questions/3548441/android-create-progressbar-programmatically –

+0

我的問題不在於設置顏色等屬性。它消失 – nikhil

+0

pb.setVisibility(View.VISIBLE); try {0} Thread.sleep(3000); pb.setVisibility(View.GONE); } catch(InterruptedException e){} –

回答

1

使用異步任務爲。在調用的onClick

new SomeTask(0).execute(); 

/** Inner class for implementing progress bar before fetching data **/ 
    private class SomeTask extends AsyncTask<Void, Void, Integer> 
    { 
     private ProgressDialog Dialog = new ProgressDialog(yourActivityClass.this); 
     @Override 
     protected void onPreExecute() 
     { 

      Dialog.setMessage("Doing something..."); 
      Dialog.show(); 
     } 

     @Override 
     protected Integer doInBackground(Void... params) 
     { 
      //Task for doing something 

      return 0; 
     } 

     @Override 
     protected void onPostExecute(Integer result) 
      { 

      if(result==0) 
      { 
//do some thing 
      } 

    // after completed finished the progressbar 
      Dialog.dismiss(); 
     } 

    } 
1

對於這個概念,你應該的AsyncTask類

上preExecute U可以設定進度可見和DoInBackGround你可以寫我們的代碼,並在PostExecute你可以設置進度歷程的可見性。

static class PleaseWait extends AsyncTask<void, void, Void> { 

final ProgressBar pb = new ProgressBar(this); pb.setVisibility(View.GONE);

protected void onPreExecute() { 
       pb.setVisibility(View.VISIBLE); 

    } 

    protected Void doInBackground(Object... args) { 
     //Write some code here 
    } 

    protected void onPostExecute(Void result) { 
     pb.setVisibility(View.GONE); 

    } 
} 

你可以調用new PleaseWait()。execute;

+0

非常感謝。但是在初始化「最終進度條」時出現錯誤 – nikhil

+0

nikhil,您應該將進度條聲明爲外部類的成員變量,否則可以在聲明中刪除最終關鍵字。它會工作。 – Hardik4560