Question

I am building some small project, it's about a game I managed to use progress bar as my hp bar in the game. It works, however, without any animation on it. Here 'damage' is an integer which is the damage to the hp bar. and hpBar is the hp bar corresponding to curHp

for( int i=0 ; i<damage ; i++){
      new Handler().postDelayed(new Runnable(){ 
        @Override
        public void run(){
            --curHp;
            hpBar.setProgress(curHp);
        }
    },40);


}

I thought there will be a 40ms delay when hp decrease by 1. But infact, if the damage is 40, the hpBar decrease at a time after 1.6s

Is there any solution about making the progressBar decrease by an amount of number and moves smoothy?

Was it helpful?

Solution

You should create the Handler() ahead of time and keep it in scope.

Also, you could sleep the thread:

for( int i=0 ; i<damage ; i++){
  new Handler().postDelayed(new Runnable(){ 
    @Override
    public void run(){
       try {
          Thread.sleep(40);
       } catch (InterruptedException e) { }
       --curHp;
        hpBar.setProgress(curHp);
    }
},40);
}

It should be said that you're likely to be get better mileage with a custom view than trying to get the ProgressBar to be your HP meter:

http://developer.android.com/training/custom-views/index.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top