android 如何从进度条获取当前值?

u1ehiz5o  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(195)

我在一个片段上设置了一个进度条动画(即计时器),每当我访问该片段时,它就会运行。我给予进度条10秒的时间从最大值(即100)减少到最小值(即0)。我的代码只显示了减少的进度条动画,而没有显示减少的数字。
下面是我的代码:

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()
    }

但是我想知道当我退出片段时剩下的秒数,而不需要把它放进动画中。例如,如果我退出片段时计时器只剩下4秒,那么它会在日志中打印4。如何做到这一点?

brccelvz

brccelvz1#

执行此操作的一种方法是访问progressBar对象的progress属性,并根据该属性计算剩余时间。

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

在您的情况下,它将是:

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

这导致:

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

相关问题