IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 仿京东首页右侧广告位,上下可拖动,伴随页面滚动显示与隐藏 -> 正文阅读

[移动开发]仿京东首页右侧广告位,上下可拖动,伴随页面滚动显示与隐藏

自定义控件继承AppCompatImageButton

控件可上下滑动需要处理控件的onTouchEvent事件 canSlide控制是否可滑动,控件隐藏不可上下滑动


    override fun onTouchEvent(event: MotionEvent): Boolean {
        super.onTouchEvent(event)
        val y = event.y.toInt()
        // 是否可滑动
        if (canSlide) {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastTop = top
                    lastX = event.x.toInt()
                    lastY = event.y.toInt()
                }
                MotionEvent.ACTION_MOVE -> {
                    val offsetY = y - lastY
                    var realTop = 0
                    var realBottom = 0
                    if (top + offsetY <= 0) {
                        realTop = 0
                        realBottom = mViewHeight
                    } else if (bottom + offsetY >= parentHeight) {
                        realTop = parentHeight - mViewHeight
                        realBottom = parentHeight
                    } else {
                        realTop = top + offsetY
                        realBottom = bottom + offsetY
                    }
                    layout(left, realTop, right, realBottom)
                }

                MotionEvent.ACTION_UP -> {
                    if (top == lastTop) {
                        clickCallBack?.invoke()
                    }
                }

            }
            return true
        } else {
            return false
        }
    }

显示与隐藏 并伴随着动画效果

/**
     * 隐藏
     */
    private fun hideButton() {
        showAnim(
            parentWith - mVieWidth * 1.0f,
            parentWith - mVieWidth * extrudeSize,
            false,
            1f,
            alphaData
        )
        showButton = false
    }

    /**
     * 显示
     */
    private fun showButton() {
        showAnim(
            parentWith - mVieWidth * extrudeSize,
            parentWith - mVieWidth * 1.0f,
            true,
            alphaData,
            1f
        )
        showButton = true
    }

    /**
     * 执行动画
     */
    private fun showAnim(
        from: Float,
        to: Float,
        enableSlide: Boolean,
        fromAlpha: Float,
        toAlpha: Float
    ) {
        val animator = ObjectAnimator.ofFloat(
            this,
            "x",
            from,
            to
        ).apply {
            interpolator = DecelerateInterpolator()
            duration = animTime.toLong()
            start()
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    super.onAnimationEnd(animation)
                    setEnableSlide(enableSlide)
                }
            })
        }
        val alphaAnimator = ObjectAnimator.ofFloat(
            this,
            "alpha",
            fromAlpha,
            toAlpha
        ).apply {
            duration = animTime.toLong()
            start()
        }

        val animatorSet = AnimatorSet()
        animatorSet.playTogether(animator, alphaAnimator)

    }

绑定滚动控件 可以是recyclerView 和NestScrollView

 /**
     * 绑定滚动的view
     */
    fun bindView(view: View?): GyMovedImageButton {
        if (view != null) {
            if (view is RecyclerView) {
                view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        if (dy > 0) {
                            if (showOrHide) {
                                hideButton()
                                showOrHide = !showOrHide
                            }

                        } else {
                            if (!showOrHide) {
                                showButton()
                                showOrHide = !showOrHide
                            }
                        }
                    }
                })
            } else if (view is NestedScrollView) {
                view.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
                    var dy = scrollY - oldScrollY
                    if (dy > 0) {
                        if (showOrHide) {
                            hideButton()
                            showOrHide = !showOrHide
                        }

                    } else {
                        if (!showOrHide) {
                            showButton()
                            showOrHide = !showOrHide
                        }
                    }

                }
            } else {
                throw Throwable("请添加绑定的View,可以是RecyclerView和NestedScrollView")
            }
        } else {
            throw Throwable("请添加绑定的View,可以是RecyclerView和NestedScrollView")
        }
        return this
    }

支持自定义属性,隐藏时控件的透明度,控件隐藏显示百分比,执行动画的时长

<declare-styleable name="GyMovedImageButton">
        <attr name="alpha" format="float" />
        <attr name="extrudeSize" format="float" />
        <attr name="animTime" format="integer" />
    </declare-styleable>

全部自定义控件代码

package com.example.myapplication.widget

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import androidx.appcompat.widget.AppCompatImageButton
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.myapplication.R

/**
 *
 *  @author wangjun
 *  @date  2021/7/27 9:47
 *  @Des  :可上下移动拖拽的广告button
 *  注意点:一定不要设置View的点击事件
 *
 */
class GyMovedImageButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageButton(context, attrs, defStyleAttr) {
    private var lastX: Int = 0
    private var lastY: Int = 0

    /**
     * 按下时的距离父控件的距离
     */
    private var lastTop: Int = 0

    /**
     * 透明度值
     */
    private var alphaData = 0.5f

    /**
     * view突出所占百分比
     */
    private var extrudeSize = 0.5f

    /**
     * 动画执行时长
     */
    private var animTime = 400

    /**
     * 当前控件的高度/宽度
     */
    private var mViewHeight: Int = 0
    private var mVieWidth: Int = 0

    /**
     * 父控件的高度/宽度
     */
    private var parentHeight: Int = 0
    private var parentWith: Int = 0

    /**
     * 是否可以滑动
     */
    private var canSlide: Boolean = true
    private var showButton: Boolean = true

    /**
     * 显示与隐藏
     */
    private var showOrHide = true

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.GyMovedImageButton)
        alphaData =
            ta.getFloat(
                R.styleable.GyMovedImageButton_alpha,
                0.5f
            )
        extrudeSize =
            ta.getFloat(
                R.styleable.GyMovedImageButton_extrudeSize,
                0.5f
            )
        animTime =
            ta.getInt(
                R.styleable.GyMovedImageButton_animTime,
                400
            )
        ta.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mViewHeight = measuredHeight
        mVieWidth = measuredWidth
        if (parent is ViewGroup) {
            parentHeight = (parent as ViewGroup).measuredHeight
            parentWith = (parent as ViewGroup).measuredWidth
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        super.onTouchEvent(event)
        val y = event.y.toInt()
        // 是否可滑动
        if (canSlide) {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastTop = top
                    lastX = event.x.toInt()
                    lastY = event.y.toInt()
                }
                MotionEvent.ACTION_MOVE -> {
                    val offsetY = y - lastY
                    var realTop = 0
                    var realBottom = 0
                    if (top + offsetY <= 0) {
                        realTop = 0
                        realBottom = mViewHeight
                    } else if (bottom + offsetY >= parentHeight) {
                        realTop = parentHeight - mViewHeight
                        realBottom = parentHeight
                    } else {
                        realTop = top + offsetY
                        realBottom = bottom + offsetY
                    }
                    layout(left, realTop, right, realBottom)
                }

                MotionEvent.ACTION_UP -> {
                    if (top == lastTop) {
                        clickCallBack?.invoke()
                    }
                }

            }
            return true
        } else {
            return false
        }
    }

    /**
     * 设置是否可以上下滑动
     */
    private fun setEnableSlide(canSlide: Boolean) {
        this.canSlide = canSlide
    }

    /**
     * 隐藏
     */
    private fun hideButton() {
        showAnim(
            parentWith - mVieWidth * 1.0f,
            parentWith - mVieWidth * extrudeSize,
            false,
            1f,
            alphaData
        )
        showButton = false
    }

    /**
     * 显示
     */
    private fun showButton() {
        showAnim(
            parentWith - mVieWidth * extrudeSize,
            parentWith - mVieWidth * 1.0f,
            true,
            alphaData,
            1f
        )
        showButton = true
    }

    /**
     * 执行动画
     */
    private fun showAnim(
        from: Float,
        to: Float,
        enableSlide: Boolean,
        fromAlpha: Float,
        toAlpha: Float
    ) {
        val animator = ObjectAnimator.ofFloat(
            this,
            "x",
            from,
            to
        ).apply {
            interpolator = DecelerateInterpolator()
            duration = animTime.toLong()
            start()
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    super.onAnimationEnd(animation)
                    setEnableSlide(enableSlide)
                }
            })
        }
        val alphaAnimator = ObjectAnimator.ofFloat(
            this,
            "alpha",
            fromAlpha,
            toAlpha
        ).apply {
            duration = animTime.toLong()
            start()
        }

        val animatorSet = AnimatorSet()
        animatorSet.playTogether(animator, alphaAnimator)

    }

    /**
     * 绑定滚动的view
     */
    fun bindView(view: View?): GyMovedImageButton {
        if (view != null) {
            if (view is RecyclerView) {
                view.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        if (dy > 0) {
                            if (showOrHide) {
                                hideButton()
                                showOrHide = !showOrHide
                            }

                        } else {
                            if (!showOrHide) {
                                showButton()
                                showOrHide = !showOrHide
                            }
                        }
                    }
                })
            } else if (view is NestedScrollView) {
                view.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
                    var dy = scrollY - oldScrollY
                    if (dy > 0) {
                        if (showOrHide) {
                            hideButton()
                            showOrHide = !showOrHide
                        }

                    } else {
                        if (!showOrHide) {
                            showButton()
                            showOrHide = !showOrHide
                        }
                    }

                }
            } else {
                throw Throwable("请添加绑定的View,可以是RecyclerView和NestedScrollView")
            }
        } else {
            throw Throwable("请添加绑定的View,可以是RecyclerView和NestedScrollView")
        }
        return this
    }

    /**
     * 设置数据
     */
    fun setImageData(img: String): GyMovedImageButton {
        Glide.with(context).load(img).into(this)
        return this
    }

    /**
     * 设置view的收起透明度
     */
    fun setBtnAlpha(alpha: Float): GyMovedImageButton {
        this.alphaData = alpha
        return this
    }

    /**
     * 设置控件突出百分比
     */
    fun setExtrudeSize(extrudeSize: Float): GyMovedImageButton {
        this.extrudeSize = extrudeSize
        return this
    }

    /**
     * 设置动画执行时长
     */
    fun setAnimTime(animTime: Int): GyMovedImageButton {
        this.animTime = animTime
        return this
    }

    private var clickCallBack: (() -> Unit)? = null

    @SuppressLint("ClickableViewAccessibility")
    fun setClickListen(block: () -> Unit) {
        this.clickCallBack = block
        this.setOnTouchListener { _, _ ->
            if (!showButton) {
                showOrHide = true
                showButton()
            }
            false
        }
    }


}

使用:

布局中:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/mParentView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.core.widget.NestedScrollView
        android:id="@+id/scrollView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:background="@color/teal_700" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:background="@color/colorAccent" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:background="@color/purple_500" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:background="@color/teal_700" />
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>

    <com.example.myapplication.widget.GyMovedImageButton
        android:id="@+id/floatButton"
        android:layout_width="100dp"
        android:layout_height="70dp"
        android:background="@color/teal_200"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:alpha="0.3"
        app:extrudeSize="0.3"/>
</androidx.constraintlayout.widget.ConstraintLayout>

支持recyclerView和NestScrollView的联动

代码调用

floatButton.bindView(rv).setClickListen {
            Toast.makeText(this@MoveButtonActivity,"点击跳转", Toast.LENGTH_SHORT).show()
        }

!!!注意使用 一定不要自已调用控件的点击事件

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-07-29 23:28:47  更:2021-07-29 23:29:05 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/20 3:25:44-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码