Why doesn't it show ProgressDialog after calling SystemClock.sleep?



  • I want to test how ProgressDialog' works and write a simple code like this:

    package com.example.aleksey.test;
    

    import android.app.ProgressDialog;
    import android.os.SystemClock;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;

    public class MainActivity extends AppCompatActivity {
    private ProgressDialog dialog;

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

    public void click(View view) {
    showProgressDialog();
    for (int i = 0; i < 10; i++) {
    SystemClock.sleep(100);
    }
    hideProgressDialog();
    }

    private void showProgressDialog() {
    if (dialog == null) {
    dialog = new ProgressDialog(this);
    dialog.setMessage(getString(R.string.saving));
    dialog.setIndeterminate(true);
    }
    dialog.show();
    }

    private void hideProgressDialog() {
    if (dialog != null && dialog.isShowing()) {
    dialog.hide();
    }
    }
    }

    Function SystemClock.sleep() He does, but why doesn't he? ProgressDialogWhat am I doing wrong?



  • Because you're launching a show of dialogue, then sliding the main flow where the entire UI works, and then launching the closure of the dialogue. As a result, UI has been frozen without being able to depict anything, and when it's dissolved, it's time to hide immediately, and it never happened.

    Anyway, you need to:

    package com.example.aleksey.test;
    

    import android.app.ProgressDialog;
    import android.os.SystemClock;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;

    public class MainActivity extends AppCompatActivity {
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void click(View view) {
        showProgressDialog();
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                hideProgressDialog();
            }
        }, 1000);
    }
    
    private void showProgressDialog() {
        if (dialog == null) {
            dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.saving));
            dialog.setIndeterminate(true);
        }
        dialog.show();
    }
    
    private void hideProgressDialog() {
        if (dialog != null &amp;&amp; dialog.isShowing()) {
            dialog.hide();
        }
    }
    

    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2