用ViewPager2实现简易的计数器
2020-04-23 本文已影响0人
超级绿茶

这是一个仿物理计数器的APP,利用手机的音量按钮实现计数,音量加就是累加一个数,音量减就是减去一个数。功能极其简单,这回仍旧用了ViewPager2的上下滚动功能。只当是练练手了。好了,不多解释了,直接上代码,相信你们都看得明白。
class MainActivity : AppCompatActivity() {
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initVPCounter()
btnReset.setOnClickListener {
count = 0
updateCounter()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> {
count++
updateCounter()
true
}
KeyEvent.KEYCODE_VOLUME_DOWN -> {
if (count > 0)
count--
updateCounter()
true
}
else -> super.onKeyDown(keyCode, event)
}
}
private fun initVPCounter() {
arrayOf(vpCount1, vpCount2, vpCount3, vpCount4).forEach {
buildCounter(it)
}
}
private fun buildCounter(vpCount: ViewPager2) {
vpCount.isUserInputEnabled = false // 禁止手滑控件
vpCount.offscreenPageLimit = 1
vpCount.orientation = ORIENTATION_VERTICAL // 垂直方向
vpCount.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_counter, parent, false)
return object : RecyclerView.ViewHolder(view) {}
}
override fun getItemCount() = 11
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.itemView.tvCounterNumber.text = (position % 10).toString()
}
}
vpCount.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrollStateChanged(state: Int) {
// 当滚动结束并且滚动到最后一页时再跳转到第一页,跳转时无动画
if (state == ViewPager2.SCROLL_STATE_IDLE && vpCount.currentItem == 10) {
vpCount.setCurrentItem(0, false)
}
}
})
}
private fun updateCounter() {
vpCount1.currentItem = count / 1000
vpCount2.currentItem = count % 1000 / 100
vpCount3.currentItem = count % 100 / 10
vpCount4.currentItem = count % 10
}
}
点击链接加入QQ群聊:https://jq.qq.com/?_wv=1027&k=5z4fzdT
或关注微信公众号:口袋里的安卓