Android采用Scroller实现底部二楼效果

2024-06-15 18:52

本文主要是介绍Android采用Scroller实现底部二楼效果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求

在移动应用开发中,有时我们希望实现一种特殊的布局效果,即“底部二楼”效果。这个效果类似于在列表底部拖动时出现额外的内容区域,用户可以继续向上拖动查看更多内容。这种效果可以用于展示广告、推荐内容或其他信息。

效果

实现后的效果如下:

  1. 当用户滑动到列表底部时,可以继续向上拖动,显示出隐藏的底部内容区域。
  2. 底部内容区域可以包含任意视图,如RecyclerView等。
  3. 滑动到一定阈值后,可以自动回弹到初始位置或完全展示底部内容。

实现思路

为了实现这一效果,我们可以自定义一个ScrollerLayout,并使用Scroller类来处理滑动和回弹动画。主要思路如下:

  1. 创建自定义的ScrollerLayout继承自LinearLayout
  2. ScrollerLayout中,遍历所有子视图,找到其中的RecyclerView,并为其添加滚动监听器。
  3. RecyclerView滚动到顶部时,允许整个布局继续向上滑动,展示底部内容区域。
  4. 使用Scroller类实现平滑滚动和回弹效果。

实现代码

ScrollerLayout.kt

package com.yxlh.androidxy.demo.ui.scrollerimport android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.LinearLayout
import android.widget.Scroller
import androidx.recyclerview.widget.RecyclerView
import com.yxlh.androidxy.R//github.com/yixiaolunhui/AndroidXY
class ScrollerLayout @JvmOverloads constructor(context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = 0,
) : LinearLayout(context, attrs, defStyleAttr) {private val mScroller = Scroller(context)private var lastY = 0private var downY = 0private var contentHeight = 0private var isRecyclerViewAtTop = falseprivate val touchSlop = ViewConfiguration.get(context).scaledTouchSlopinit {orientation = VERTICALpost {setupRecyclerViews()}}private fun setupRecyclerViews() {for (i in 0 until childCount) {val child = getChildAt(i)if (child is RecyclerView) {child.addOnScrollListener(object : RecyclerView.OnScrollListener() {override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {isRecyclerViewAtTop = !recyclerView.canScrollVertically(-1)}})}}}override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {super.onLayout(changed, l, t, r, b)val bottomBar = getChildAt(0)contentHeight = 0for (i in 0 until childCount) {val child = getChildAt(i)if (child is RecyclerView) {contentHeight += child.measuredHeight}}bottomBar.layout(0, measuredHeight - bottomBar.measuredHeight, measuredWidth, measuredHeight)for (i in 1 until childCount) {val child = getChildAt(i)if (child is RecyclerView) {child.layout(0, measuredHeight, measuredWidth, measuredHeight + contentHeight)}}}override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {val isTouchChildren = isTouchInsideChild(ev)Log.d("121212", "onInterceptTouchEvent isTouchChildren=$isTouchChildren")when (ev.action) {MotionEvent.ACTION_DOWN -> {downY = ev.y.toInt()lastY = downY}MotionEvent.ACTION_MOVE -> {val currentY = ev.y.toInt()val dy = currentY - downYif (isRecyclerViewAtTop && dy > touchSlop) {lastY = currentYreturn true}}}return super.onInterceptTouchEvent(ev)}override fun onTouchEvent(event: MotionEvent): Boolean {when (event.action) {MotionEvent.ACTION_DOWN -> {if (!isTouchInsideChild(event)) return falseif (!mScroller.isFinished) {mScroller.abortAnimation()}lastY = event.y.toInt()return true}MotionEvent.ACTION_MOVE -> {if (!isTouchInsideChild(event)) return falseval currentY = event.y.toInt()val dy = lastY - currentYval scrollY = scrollY + dyif (scrollY < 0) {scrollTo(0, 0)} else if (scrollY > contentHeight) {scrollTo(0, contentHeight)} else {scrollBy(0, dy)}lastY = currentYreturn true}MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {val threshold = contentHeight / 2if (scrollY > threshold) {showNavigation()} else {closeNavigation()}return true}}return false}private fun isTouchInsideChild(event: MotionEvent): Boolean {val x = event.rawX.toInt()val y = event.rawY.toInt()for (i in 0 until childCount) {val child = getChildAt(i)if (isViewUnder(child, x, y)) {return true}}return false}private fun isViewUnder(view: View?, x: Int, y: Int): Boolean {if (view == null) return falseval location = IntArray(2)view.getLocationOnScreen(location)val viewX = location[0]val viewY = location[1]return x >= viewX && x < viewX + view.width && y >= viewY && y < viewY + view.height}fun showNavigation() {val dy = contentHeight - scrollYmScroller.startScroll(scrollX, scrollY, 0, dy, 500)invalidate()}private fun closeNavigation() {val dy = -scrollYmScroller.startScroll(scrollX, scrollY, 0, dy, 500)invalidate()}override fun computeScroll() {if (mScroller.computeScrollOffset()) {scrollTo(mScroller.currX, mScroller.currY)postInvalidateOnAnimation()}}
}

ScrollerActivity.kt

package com.yxlh.androidxy.demo.ui.scrollerimport android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.yxlh.androidxy.R
import com.yxlh.androidxy.databinding.ActivityScrollerBinding
import kotlin.random.Randomclass ScrollerActivity : AppCompatActivity() {private var binding: ActivityScrollerBinding? = nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityScrollerBinding.inflate(layoutInflater)setContentView(binding?.root)//内容布局binding?.content?.layoutManager = LinearLayoutManager(this)binding?.content?.adapter = ColorAdapter(false)//底部布局binding?.bottomContent?.layoutManager = LinearLayoutManager(this)binding?.bottomContent?.adapter = ColorAdapter(true)binding?.content?.addOnScrollListener(object : RecyclerView.OnScrollListener() {override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {if (!recyclerView.canScrollVertically(1) && newState == RecyclerView.SCROLL_STATE_IDLE) {binding?.scrollerLayout?.showNavigation()}}})}
}class ColorAdapter(private var isColor: Boolean) : RecyclerView.Adapter<ColorAdapter.ColorViewHolder>() {private val colors = List(100) { getRandomColor() }override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ColorViewHolder {val view = LayoutInflater.from(parent.context).inflate(R.layout.item_color, parent, false)return ColorViewHolder(view, isColor)}override fun onBindViewHolder(holder: ColorViewHolder, position: Int) {holder.bind(colors[position], position)}override fun getItemCount(): Int = colors.sizeprivate fun getRandomColor(): Int {val random = Random.Defaultreturn Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256))}class ColorViewHolder(itemView: View, private var isColor: Boolean) : RecyclerView.ViewHolder(itemView) {fun bind(color: Int, position: Int) {if (isColor) {itemView.setBackgroundColor(color)}itemView.findViewById<TextView>(R.id.color_tv).text = "$position"}}
}

结束

通过上述代码,我们成功实现了底部二楼效果。在用户滑动到RecyclerView底部时,可以继续向上拖动以显示底部的内容区域。这种效果可以增强用户体验,增加更多的内容展示方式。通过自定义布局和使用Scroller类,我们可以轻松实现这种复杂的滑动效果。
详情:github.com/yixiaolunhui/AndroidXY

这篇关于Android采用Scroller实现底部二楼效果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1064286

相关文章

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Nexus安装和启动的实现教程

《Nexus安装和启动的实现教程》:本文主要介绍Nexus安装和启动的实现教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Nexus下载二、Nexus安装和启动三、关闭Nexus总结一、Nexus下载官方下载链接:DownloadWindows系统根

SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程

《SpringBoot集成LiteFlow实现轻量级工作流引擎的详细过程》LiteFlow是一款专注于逻辑驱动流程编排的轻量级框架,它以组件化方式快速构建和执行业务流程,有效解耦复杂业务逻辑,下面给大... 目录一、基础概念1.1 组件(Component)1.2 规则(Rule)1.3 上下文(Conte

MySQL 横向衍生表(Lateral Derived Tables)的实现

《MySQL横向衍生表(LateralDerivedTables)的实现》横向衍生表适用于在需要通过子查询获取中间结果集的场景,相对于普通衍生表,横向衍生表可以引用在其之前出现过的表名,本文就来... 目录一、横向衍生表用法示例1.1 用法示例1.2 使用建议前面我们介绍过mysql中的衍生表(From子句