如何重新启动水平进度条

how to restart horizontal progressbar

我有一个水平进度条,显示从 0 到 100 的进度。我想要的是当进度条达到 100 时从 0 重新启动进度条。我将在 Fragmentdialog 中显示它。现在我正在检查 activity 本身。怎么做?

    public class MainActivity extends AppCompatActivity{
    private Button startbtn, stopbtn;
    ProgressBar pb;
    private TextView progressTxt;

    int progressBarValue = 0;
    Handler handler = new Handler();

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


        setContentView(R.layout.activity_main);
        show = new CShowProgress(MainActivity.this);

        btn = (Button)findViewById(R.id.btn);
        startbtn = (Button)findViewById(R.id.startbtn);
        stopbtn = (Button)findViewById(R.id.stopbtn);
        pb = (ProgressBar)findViewById(R.id.progressBar);
        progressTxt = (TextView)findViewById(R.id.progressTxt);

        startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(true);
            }
        });

        stopbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myprogress(false);
            }
        });
    }

    private void myprogress(final Boolean isStart){
        handler = new Handler()
        {
            public void handleMessage(android.os.Message msg)
            {
                if(isStart && progressBarValue<100)
                {
                    progressBarValue+=1;
                    pb.setProgress(progressBarValue);
                    progressTxt.setText(String.valueOf(progressBarValue));

                    handler.sendEmptyMessageDelayed(0, 100);
                }

            }
        };

        handler.sendEmptyMessage(0);
    }
}

首先,您应该使用计数器机制(运行 延迟处理程序、计时器、线程或其他东西)定期检查当前进度。

 (progressTxt.getProgress == 100)

会成功的。

另一种方法是使用 this answer

我假设这段代码适用于您的用例:

private void myprogress(final Boolean isStart) {
  handler = new Handler() {
    public void handleMessage(Message msg) {
      if (isStart && progressBarValue < 100) {
          ...
      } else if (isStart) {
        // progressBarValue is equal to 100
        // make it zero and do the same thing again
        progressBarValue = 0;
        progressBarValue += 1;
        pb.setProgress(progressBarValue);
        progressTxt.setText(String.valueOf(progressBarValue));

        handler.sendEmptyMessageDelayed(0, 100);
      }
    }
  };

  handler.sendEmptyMessage(0);
}