[Android] custom ProgressDialog to temporarily hide the progress value and display the waiting status (with source code download), androiddialog

Source: Internet
Author: User

[Android] custom ProgressDialog to temporarily hide the progress value and display the waiting status (with source code download), androiddialog

Sometimes, we need to access the network to get the number of tasks to be operated (such as the number of files downloaded), and to hide the progress percentage and progress value before the server returns the number of tasks, we need to rewrite ProgressDialog by ourselves. After obtaining the number of tasks, the Progress value and percentage are displayed. First:

Key code:

public class CustomProgressDialog extends ProgressDialog {private final String TAG = this.getClass().getSimpleName();public CustomProgressDialog(Context context) {    super(context);}public CustomProgressDialog(Context context, int theme) {super(context, theme);// TODO Auto-generated constructor stub}@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);hideNumerAndPercent();}private void hideNumerAndPercent() {setNumerPercentState(View.INVISIBLE);}public void showNumerAndPercent() {setNumerPercentState(View.VISIBLE);}private void setNumerPercentState(int visibility) {    try {        Method method = TextView.class.getMethod("setVisibility",                Integer.TYPE);        Field numField = this.getClass().getSuperclass()                .getDeclaredField("mProgressNumber");        numField.setAccessible(true);        TextView numTextView = (TextView) numField.get(this);        method.invoke(numTextView, visibility);        Field percentField = this.getClass().getSuperclass()        .getDeclaredField("mProgressPercent");        percentField.setAccessible(true);        TextView percentTextView = (TextView) percentField.get(this);        method.invoke(percentTextView, visibility);            } catch (Exception e) {        Log.e(TAG,                "Failed to invoke the progressDialog method 'setVisibility' and set 'mProgressNumber' to GONE.",                e);    }}}

Test code:

Public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); new TestTask (this, null0000.exe cute ("test");} public class TestTask extends AsyncTask <String, Integer, Void> {private Context context; private Handler mHandler; private CustomProgressDialog pd; private final int SHOW_NUMBER = 1; private final int PROGRESS_INCREMENT = 2; private final int FAIL =-1; public TestTask (Context context, Handler handler) {this. context = context; this. mHandler = handler;} @ Override protected void onPostExecute (Void result) {// TODO Auto-generated method stub super. onPostExecute (result); if (pd! = Null) {pd. cancel () ;}@ Override protected void onPreExecute () {// TODO Auto-generated method stub super. onPreExecute (); pd = new CustomProgressDialog (context); pd. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); pd. setCancelable (false); pd. setTitle ("in sync"); pd. setMessage ("Please wait, synchronizing data... "); pd. setIndeterminate (true); pd. show () ;}@ Override protected Void doInBackground (String... params) {try {/* simulate the time required to obtain the task count from the server */Thread. sleep (3000);} catch (InterruptedException e) {e. printStackTrace ();}/* Number of tasks, actually returned by the server */int count = 4; publishProgress (SHOW_NUMBER, count); int I = 0; while (I <count) {try {/* simulate the time consumed by each task */Thread. sleep (1400); publishProgress (PROGRESS_INCREMENT, 1);} catch (InterruptedException e) {e. printStackTrace ();} I ++;} return null;} @ Overrideprotected void onProgressUpdate (Integer... values) {// TODO Auto-generated method stubsuper. onProgressUpdate (values); switch (values [0]) {case SHOW_NUMBER: pd. setMax (values [1]); pd. showNumerAndPercent (); pd. setIndeterminate (false); break; case PROGRESS_INCREMENT: pd. setProgress (pd. getProgress () + values [1]); break; default: break ;}}}}

Source code download: source code download

The ProgressDialog dialog box that comes with the android system shows that the size of the downloaded file cannot be customized.

Use ProgressDialog. setMax to set the maximum value. The system defaults to 100.

The error message "ProgressDialog" is displayed when Android accesses the server over the mobile phone.

For network requests in android, timeout occurs if no response is received within 5 seconds. You should check the timeout. If the timeout occurs, the system prompts that the user request times out and whether to try again, instead of caching the dialog box all the time, this is just my idea to solve this problem. I hope it will help you. I just knocked on the code myself and I just knocked on a few paragraphs for others, I hope you can continue your work.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.