这里以recyclerview为例:
做的还是有点粗糙,里面用了一个recyclerview 和imageview实现:
var downX = 0f
var downY = 0f
var moveX = 0f
var moveY = 0f
var isStart = true
/**属性动画*/
val objTranslateAnimation = ObjectAnimator.ofFloat(img_right, "translationX", 0f, 200f)
objTranslateAnimation.duration = 1000
val objTranslateAnimation2 = ObjectAnimator.ofFloat(img_right, "translationX", 200f, 0f)
objTranslateAnimation2.duration = 1000
val lists = mutableListOf<String>()
for (it in 0..500) {
lists.add("$it")
}
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = object : BaseRecyclerAdapter<String>(this, R.layout.item_recyc, lists) {
override fun bindData(holder: SuperHolder, position: Int, bean: String?) {
val name = holder.getView<TextView>(R.id.tv_name)
name.text = bean
}
}
//第一个方法
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy != 0){//不等于相当于在滑动过程
if (isStart) {
isStart = false
objTranslateAnimation.start()
}
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {//这个是一个状态判断,这是停止的时候执行
isStart = true
if (isStart) {
objTranslateAnimation2.start()
}
}
}
})
//第二个方法,用到的是手势方法,这个方法没有第一个好,滑动过程中如果还没有停止,第二方法是滑动停止手势立即抬起,就会执行第二动画,而第一个方法是等滑动停止之后才执行第二动画,看起来要友好一点
recycler.setOnTouchListener { p0, p1 ->
when (p1?.action) {
MotionEvent.ACTION_DOWN -> {
downX = p1.x
downY = p1.y
}
MotionEvent.ACTION_MOVE -> {
moveX = p1.x
moveY = p1.y
if (downY - moveY > 50 && Math.abs(downY - moveY) > 50) {//向下
if (isStart) {
isStart = false
objTranslateAnimation.start()
}
} else if (downY - moveY < 0 && Math.abs(downY - moveY) > 50) {//向上
if (isStart) {
isStart = false
objTranslateAnimation.start()
}
}
}
MotionEvent.ACTION_UP -> {
if (downY - moveY > 50 && Math.abs(downY - moveY) > 50) {//向下
isStart = true
if (isStart) {
objTranslateAnimation2.start()
}
} else if (downY - moveY < 0 && Math.abs(downY - moveY) > 50) {//向上
isStart = true
if (isStart) {
objTranslateAnimation2.start()
}
}
}
}
false
}
以上两个皆可执行。这个例子比较简单也花了不少时间,说明还是知识积累不够!!!