简体   繁体   中英

How to show a progress bar on screen programatically in Android?

I have a class named BookAdder . It extends AsyncTask and it should add a list of books on the app. Also some activities call it and I want to show a progress bar on center of screen when it is called.

Now, I don't know how can show a progress bar without it defines in XML file of activities? Are there any way to create a progress bar then add it for showing or not?

Thanks

Try this

    new asyncTask(Your_context).execute();


    private class asyncTask extends AsyncTask<Void, Void, Boolean> 
    {
        Context context;
        ProgressDialog pd;

        asyncTask(Context context)
        {
            this.context = context; 
            pd = new ProgressDialog(activityContext);
        } 
        protected void onPreExecute() 
        {
            pd.setTitle("Loading..");
            pd.setMessage("Please wait ...");
            pd.setCancelable(false);
            pd.show();
        } 
        protected void onPostExecute(Boolean result)
        {
                   // Update your UI. 
            if(pd.isShowing()) pd.dismiss();
        } 

        @Override
        protected Boolean doInBackground(Void... params) 
        {
               // Get all data from web.
        }

@Override
        protected void onProgressUpdate(String... values) 
        {
            super.onProgressUpdate(values);

            pd.setMessage("Please Wait..." + values[0].toString());
        }

        public class Progress 
        {
            public asyncTask task;

            public Progress(asyncTask task) 
            {
                this.task = task;
            }

            public void publish(String value) 
            {
                task.publishProgress(value);
            }
        }
    }

Try to call progress update with publishProgress(updating_values);

You can do it like this:

new DownloadData(yourClass.this).execute();


public class DownloadData extends AsyncTask<Void,Void,Void>
{
  ProgressBar pBar;
  Context context;

    public DownloadData(context con)
    {
            context = con;
             pBar = new ProgressBar(context);
            LinearLayout layout = (LinearLayout) context.findViewById(R.id.ProgressBar);
            layout.addView(pBar);
            pBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackgroud(Void.. params)
    {
        // download data
    }


@Override
protected void onPostExecute(Void result) 
{
    super.onPostExecute(result);
    if (pBar!=null) {
        ((LinearLayout)pBar.getParent()).removeView(pBar);
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM