View向上滑动指定距离进行指定操作

251 阅读1分钟
  1. 此view是自定义view,用户可以修改其继承的父类
package com.k.android.view

import android.animation.Animator
import android.animation.ObjectAnimator
import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.MotionEvent
import com.k.android.utils.Log
import com.k.android.utils.Utils

class SlideTopView(context: Context,attr: AttributeSet):ConstraintLayout(context,attr){
    private var lastY = 0;
    var animation:ObjectAnimator?=null
    var downTime:Long?=null
    private var onSlideTopListener:()->Unit={}
    private var onClickListener:()->Unit={}
    override fun onTouchEvent(event: MotionEvent): Boolean {
        val y = event.rawY.toInt()

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastY = y
                downTime = System.currentTimeMillis()
            }
            MotionEvent.ACTION_MOVE -> {
                var offsetY = y - lastY
                if(top+offsetY>0){//只能向上滑动
                    offsetY=0
                }
                layout(left,top + offsetY,right,bottom + offsetY)
                lastY = y
            }
            MotionEvent.ACTION_UP -> {
                if(top>-height/2){
                    startAnim(0)
                }else{
                    startAnim(-height)
                }
                if(downTime!=null&&System.currentTimeMillis()-downTime!!<500&&-top<Utils.dp2px(3f)){
                    //0是取消显示 1是点击跳转
                    onClickListener()
                }
            }
        }
        return true
    }

    /**
     * 设置动画移动偏移量
     */
    fun startAnim(offSet:Int){
        animation = ObjectAnimator.ofInt(this,"offset",top,offSet)
        var i=top-offSet.toLong()
        animation?.duration = if(i>0) i else -i
        animation?.addListener(object:Animator.AnimatorListener{
            override fun onAnimationRepeat(animation: Animator?) {
            }

            override fun onAnimationEnd(animation: Animator?) {
                // !=0 证明移出界面则执行监听
                if(offSet!=0){
                    onSlideTopListener()
                }
            }

            override fun onAnimationCancel(animation: Animator?) {
            }

            override fun onAnimationStart(animation: Animator?) {
            }

        })
        animation?.start()
    }

    /**
     * 设置动画执行的内容
     */
    fun setOffset(offset: Int) {
        Log.i("share","offset=$offset")
        layout(left,offset,right,offset+height)
    }

    /**
     * 设置向上移动到顶部的监听
     */
    fun setOnSlideTop(onSlideTopListener:()->Unit){
        this.onSlideTopListener = onSlideTopListener;
    }

    /**
     * 设置点击监听
     */
    fun setOnClickListener(onClickListener:()->Unit){
        this.onClickListener = onClickListener;
    }
}