目录
效果展示
这里有两种效果,一个是每次滑动一个条目,另一个是持续向上滑动
实现方法
两种效果的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EEE"
tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_flipper_one"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="210dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_flipper_two"
android:layout_marginTop="30dp"
android:nestedScrollingEnabled="false"
android:layout_width="match_parent"
android:layout_height="210dp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</layout>
第一种效果
第一种效果是使用动画实现的
/**
* 滑动公告
*/
private fun initFlipperOne(testData: ArrayList<FlipperBean>) {
binding.rvFlipperOne.layoutManager = LinearLayoutManager(this)
binding.rvFlipperOne.adapter = FlipperAdapter(testData,this)
var oldAnimValue = -1
//获取单个条目的高度,通过高度执行动画
val animator = ValueAnimator.ofInt(0,dip2px(35f))
animator.addUpdateListener {
//获取动画的值,用于滚动(因为使用的是scrollBy因此每次滚动的是与上一次的差值)
val value:Int = it.animatedValue as Int
if(oldAnimValue == -1){
oldAnimValue = value
binding.rvFlipperOne.scrollBy(0,value)
}else{
binding.rvFlipperOne.scrollBy(0,value - oldAnimValue)
oldAnimValue = value
}
}
animator.addListener(onEnd = {
//动画结束的时候,间歇1秒继续执行动画
oldAnimValue = -1
handler.postDelayed({
animator.start()
},1000)
})
animator.duration = 1000
animator.start()
}
// 根据手机的分辨率从 dp 的单位 转成为 px(像素)
private fun dip2px(dpValue:Float):Int {
// 获取当前手机的像素密度(1个dp对应几个px)
val scale = resources.displayMetrics.density
return ((dpValue * scale + 0.5f).toInt()) // 四舍五入取整
}
第二种效果
第二种效果是使用handler循环执行任务实现的
/**
* 滑动公告
*/
private fun initFlipperTwo(testData: ArrayList<FlipperBean>) {
binding.rvFlipperTwo.layoutManager = LinearLayoutManager(this)
binding.rvFlipperTwo.adapter = FlipperAdapter(testData,this)
handler.postDelayed(runnable,50)
}
private val runnable = object : Runnable{
override fun run() {
//持续滚动
binding.rvFlipperTwo.scrollBy(0,3)
handler.postDelayed(this,50)
}
}
案例源码
源码上传在码云,由于码云的政策变换,开放比较麻烦,我这只是贴在这方便自己以后查看
https://gitee.com/itfitness/auto-scroll
网友评论