利用kotlin扩展函数来实现优雅的防重点,如果对kotlin扩展函数没有太多了解的可以先看一下资料,本案例RecyclerView的adapter采用BaseRecyclerViewAdapterHelper框架
直接上代码,新建一个kt文件,把以下代码拷进去:
private object SingleClickObject {
var delayTime = 0L
//由于共用一个last,会造成点击完一个,快速去点击另一个,也会被屏蔽,可以维护多个变量来解决
var lastClickTime = 0L
}
/**
* view防重点
*/
fun <T : View> T.singleClick(time: Long = 1000, block: (T) -> Unit) {
SingleClickObject.delayTime = time
setOnClickListener {
if (clickEnable()) {
block(it as T)
}
}
}
/**
* BaseQuickAdapter item防重点
*/
fun <T> BaseQuickAdapter<T, BaseViewHolder>.singleItemClick(time: Long = 1000, block: (position: Int) -> Unit) {
SingleClickObject.delayTime = time
setOnItemClickListener { _, _, position ->
if (clickEnable()) {
block(position)
}
}
}
/**
* BaseQuickAdapter item子view防重点
*需要什么字段回调,自己加,这里由于只需要view的id,所以另外两个没有用
*/
fun <T> BaseQuickAdapter<T, BaseViewHolder>.singleChildItemClick(time: Long = 1000, block: (viewId: Int) -> Unit) {
SingleClickObject.delayTime = time
setOnItemChildClickListener { _, view, _ ->
if (clickEnable()) {
block(view.id)
}
}
}
/**
* 是否可点击
*/
private fun clickEnable(): Boolean {
var flag = false
val currentClickTime = System.currentTimeMillis()
if (currentClickTime - SingleClickObject.lastClickTime >= SingleClickObject.delayTime) {
SingleClickObject.lastClickTime = currentClickTime
flag = true
}
System.out.println(flag)
return flag
}
//tabLayout的选中监听
fun <T : TabLayout> T.tabSelected(block: (position: Int) -> Unit) {
addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(p0: TabLayout.Tab?) {
}
override fun onTabUnselected(p0: TabLayout.Tab?) {
}
override fun onTabSelected(p0: TabLayout.Tab) {
block(p0.position)
}
})
}
使用:
//实例化adapter
val adapter = QuickAdapter()
val data = ArrayList<String>()
rv_main.layoutManager = LinearLayoutManager(this)
rv_main.adapter = adapter
data.apply {
add("测试1")
add("测试2")
add("测试3")
add("测试4")
}
adapter.setNewData(data)
//TextView点击
tv_click.singleClick {
Log.d("测试view", System.currentTimeMillis().toString())
}
//自定义间隔
tv_click.singleClick(500) {
Log.d("测试view(间隔500毫秒)", System.currentTimeMillis().toString())
}
//RecyclerView的item点击
adapter.singleItemClick {
Log.d("测试item", System.currentTimeMillis().toString())
}
//RecyclerView的ChildView点击
adapter.singleChildItemClick {
if (it == R.id.bt_test) {
Log.d("测试child", System.currentTimeMillis().toString())
}
}
//tabLayout选中
tl_year.tabSelected {
Log.d("tabLayout选中的位置:",it)
}
也可以采用aspectj进行AOP切面,来防重点,各有各的优势,在正在开发的项目中,两种方式都在用,这里就不一一介绍了!
完,有问题随时沟通~!
网友评论