Home > Mobile >  How to get current value from progress bar?
How to get current value from progress bar?

Time:11-19

I have a progress bar animation (i.e. timer) on a fragment that will be run every time I access that fragment. I give the progress bar 10 seconds to decrease from max (i.e. 100) to min (i.e. 0). My code only shows the decreasing bar animation without showing the decreasing number.

Here is my code :

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            val binding = DataBindingUtil.inflate<FragmentGameBinding>(
                inflater, R.layout.fragment_game, container, false)
    
            binding.game = this
            timer(binding)
            
            // when user clicks submitButton, it will exit current fragment
            binding.submitButton.setOnClickListener{ view: View ->
               Log.d("asd","print seconds left when exit the fragment : ") //print here
               view.findNavController().navigate(GameFragmentDirections.actionGameFragmentToGameOverFragment())
            }
            
            return binding.root
    }
    private fun timer(binding:FragmentGameBinding){
        val mProgressBar = binding.progressBar
        val progressAnimator = ObjectAnimator.ofInt(mProgressBar, "progress", 100, 0) //max 100, min 0
        progressAnimator.duration = 10000 //10 s = 10000 ms
        progressAnimator.interpolator = LinearInterpolator()
        progressAnimator.start()
    }

But I want to get the number of seconds left when I exit the fragment without have to put it into animation. For example, If I exit the fragment when the timer only left with 4 seconds, then it will print 4 in the Log. How to do this?

CodePudding user response:

One way of doing this is accessing the progress property of the progressBar object and calculating time left based on that.

button.setOnClickListener {
    Log.d("MainActivity", "${(progressBar.progress * maximumNumberOfSeconds) / 100} seconds left")
}

which in your case would be:

button.setOnClickListener {
    Log.d("MainActivity", "${(progressBar.progress * 10) / 100} seconds left")
}

which results in:

2022-11-19 11:23:31.138 10076-10076/com.example.streamchat D/MainActivity: 8 seconds left
2022-11-19 11:23:31.891 10076-10076/com.example.streamchat D/MainActivity: 8 seconds left
2022-11-19 11:23:32.524 10076-10076/com.example.streamchat D/MainActivity: 7 seconds left
2022-11-19 11:23:33.172 10076-10076/com.example.streamchat D/MainActivity: 6 seconds left
2022-11-19 11:23:33.802 10076-10076/com.example.streamchat D/MainActivity: 6 seconds left
2022-11-19 11:23:34.437 10076-10076/com.example.streamchat D/MainActivity: 5 seconds left
2022-11-19 11:23:35.058 10076-10076/com.example.streamchat D/MainActivity: 5 seconds left
2022-11-19 11:23:35.610 10076-10076/com.example.streamchat D/MainActivity: 4 seconds left
  • Related