当前位置: 首页 > news >正文

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

相关文章:

  • ndk-build
  • JS读取目录下的所有图片/require动态加载图片/文字高亮
  • MySQL-连接查询
  • 正则表达式规则以及贪婪匹配与非贪婪匹配详解
  • HTML5的未来:掌握最新技术,打造炫酷网页体验
  • 易灸灸的微商模式,新零售全案运营,裂变营销与代理模式
  • 【LinkedList与链表】
  • 基于单片机的太阳能无线 LED 灯设计
  • 2024FIC决赛
  • web安全渗透测试十大常规项(一):web渗透测试之XML和XXE外部实体注入
  • 赛氪网受邀参加上海闵行区翻译协会年会,共探科技翻译创新之路
  • 什么是DMZ?路由器上如何使用DMZ?
  • LabVIEW开发EOL功能测试系统
  • C# —— switch语句
  • 59.WEB渗透测试-信息收集- 端口、目录扫描、源码泄露(7)
  • [Vue CLI 3] 配置解析之 css.extract
  • 【mysql】环境安装、服务启动、密码设置
  • JavaScript DOM 10 - 滚动
  • JavaScript的使用你知道几种?(上)
  • JSONP原理
  • mockjs让前端开发独立于后端
  • redis学习笔记(三):列表、集合、有序集合
  • Storybook 5.0正式发布:有史以来变化最大的版本\n
  • 技术发展面试
  • 精彩代码 vue.js
  • 离散点最小(凸)包围边界查找
  • 怎么把视频里的音乐提取出来
  • 从如何停掉 Promise 链说起
  • 交换综合实验一
  • 如何在招聘中考核.NET架构师
  • ​2020 年大前端技术趋势解读
  • (173)FPGA约束:单周期时序分析或默认时序分析
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (C语言)strcpy与strcpy详解,与模拟实现
  • (编程语言界的丐帮 C#).NET MD5 HASH 哈希 加密 与JAVA 互通
  • (第8天)保姆级 PL/SQL Developer 安装与配置
  • (附源码)springboot电竞专题网站 毕业设计 641314
  • (原創) 人會胖會瘦,都是自我要求的結果 (日記)
  • (转)shell中括号的特殊用法 linux if多条件判断
  • (转)我也是一只IT小小鸟
  • (转载)PyTorch代码规范最佳实践和样式指南
  • .Net Web项目创建比较不错的参考文章
  • .NET/C# 使窗口永不获得焦点
  • .NET分布式缓存Memcached从入门到实战
  • .NET和.COM和.CN域名区别
  • ::前边啥也没有
  • ??在JSP中,java和JavaScript如何交互?
  • @NoArgsConstructor和@AllArgsConstructor,@Builder
  • [ 隧道技术 ] cpolar 工具详解之将内网端口映射到公网
  • [AIR] NativeExtension在IOS下的开发实例 --- IOS项目的创建 (一)
  • [BFS广搜]迷阵
  • [BZOJ 4034][HAOI2015]T2 [树链剖分]
  • [BZOJ 4598][Sdoi2016]模式字符串
  • [Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated c
  • [go] 迭代器模式