单击按钮时的进度条

Progressbar on button click

所以代码中的一切都有效,但我无法弄清楚如何通过单击按钮一次增加 1 个单位的进度条。

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Chronometer;
import android.view.View.OnClickListener;
import android.os.SystemClock;
import android.widget.ProgressBar;

public class MainActivity extends Activity{

        TextView txtCount;
        Button btnCount;
        int count=0;
        Chronometer chrono;
        boolean mIsStarted = false;
        ProgressBar probar;

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

            chrono=(Chronometer) findViewById(R.id.chronometer);
            txtCount=(TextView) findViewById(R.id.textView);
            btnCount=(Button)findViewById(R.id.button);
            probar=(ProgressBar) findViewById(R.id.progressBar);

            btnCount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    count++;
                    txtCount.setText(String.valueOf(count));
                    btnCount.setEnabled(true);
                    if (!mIsStarted) {
                        chrono.setBase(SystemClock.elapsedRealtime());
                        chrono.start();
                        mIsStarted = true;

                        probar.setProgress(count++);
                        probar.setMax(5);


                    }
                }
        });
    }}

几个小时以来,我一直在尝试一些愚蠢的事情,但无法让它发挥作用。它将计算第一次点击,但随后停止计算后续点击。我认为它的工作方式类似于 textview 方法,但仍然无法弄清楚!感谢您的回答!

It will count the first click but then stops counting the following clicks

由于 if 块:

 if (!mIsStarted) {
  ...
  mIsStarted = true;
  ...
}

因为 mIsStarted 仅是第一次 falsemIsStarted 的其余值是 true.

因此,要么删除 if 条件,要么将 ProgressBar 相关代码移到 if 块之外,使其在单击按钮时起作用。

是因为你的onClick()方法中有这个条件

mIsStarted = true;

首先看到您已将 mIsStarted 初始化为 false 所以它在第一次点击时工作但是一旦它进入这里的这种情况

 if (!mIsStarted) {
                    chrono.setBase(SystemClock.elapsedRealtime());
                    chrono.start();
                    mIsStarted = true; // here it is initialized to true

                    probar.setProgress(count++);
                    probar.setMax(5);


                }

所以现在 mIsStartedtrue 所以它不会进入上面的 if 因此不会增加 progress bar

所以你可以评论这条语句mIsStarted = true;然后检查