问题描述:

So everything works in the code but i can not figure out how to increase the progressbar 1 unit at a time with the button clicks.

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);

}

}

});

}}

I have been trying a stupid amount of things for hours and can not get it to work. It will count the first click but then stops counting the following clicks. I figured it would work similar to the textview methods but still can not figure it out! thanks for your answers!

网友答案:

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

Due to if block:

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

Because mIsStarted is false for first time only and for rest value of mIsStarted is true.

So either remove if condition or move ProgressBar related code outside if block to get it work on Button click.

网友答案:

It is because of this condition in your onClick() method

mIsStarted = true;

See at first you have initialized mIsStarted to false so it works in first click but once it gets inside this condition here

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

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


                }

so now mIsStarted is true so it will not enter the above if and hence wont inrement the progress bar

So you can comment this statement mIsStarted = true; and then check

相关阅读:
Top