我有一个像progressBar的倒计时,我想在buttonClick上增加它的进度。 问题是进展在增加,但只是在视觉上。如果进度降低到60并且按下按钮增加它应该是80,但相反,进度从60而不是80递减。 这是我的代码:
public class MainActivity extends AppCompatActivity {
ProgressBar timeLeft;
CountDownTimer gameCountDownTimer;
Button increment;
int progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeLeft = (ProgressBar) findViewById(R.id.timeLeft);
increment = (Button) findViewById(R.id.increment);
timeLeft.setMax(100);
setTimer(10);
increment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timeLeft.incrementProgressBy(20);
}
});
}
private void setTimer(int time) {
progress = 100;
final int actualTime = time*1000;
timeLeft.setProgress(progress);
gameCountDownTimer = new CountDownTimer(actualTime, 1000) {
int totalTime = actualTime;
@Override
public void onTick(long millisUntilFinished) {
progress = (int)( millisUntilFinished /(double)totalTime * 100);
timeLeft.setProgress(progress);
}
@Override
public void onFinish() {
progress = 0;
timeLeft.setProgress(progress);
}
}.start();
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".Main">
<ProgressBar
android:id="@+id/timeLeft"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:progress="100"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Increment"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
答案 0 :(得分:0)
使用postDelayed方法代替使用计时器:
int interval=1000;
int totalTime=10000;
timeLeft.postDelayed(new Runnable() {
@Override
public void run() {
currentTime+=interval;
timeLeft.setProgress(timeLeft.getProgress()-(timeLeft.getMax()/totalTime)*interval);
if(timeLeft.getProgress>0){
timeLeft.postDelayed(this,interval);
}
}
}, interval);
答案 1 :(得分:0)
尝试此进度计算。例如,取millisUntilFinished是5000 和totalTime是10000。
然后进展应该是50。在你的情况下,它是(int)0.005,这就是0,这就是你的进度条在单点上停留的原因。
@Override
public void onTick(long millisUntilFinished) {
progress = (int)( (millisUntilFinished* 100 ) /(double)totalTime);
timeLeft.setProgress(progress);
}