Android自定义viewgroup快速滑动(4)

发布时间 - 2026-01-10 21:58:16    点击率:

上一篇文章自定义viewgroup(3)地址:https://www./article/100618.htm

代码:

package com.example.libingyuan.horizontallistview.ScrollViewGroup;

import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Scroller;

/**
 * 自定义ViewGroup
 * 增加了加速度滑动
 */
public class ScrollViewGroup extends ViewGroup {
  //滚动计算辅助类
  private Scroller mScroller;
  //手指落点的X坐标
  private float mLastMotionX = 0;
  //屏幕宽度
  private int screenWidth;
  //手指加速度辅助类
  private VelocityTracker mVelocityTracker;
  //每秒移动的最小dp
  private int mMinimumVelocity;
  //每秒移动的最大dp
  private int mMaximumVelocity;

  /**
   * 使用new关键字创建对象的时候调用
   *
   * @param context 上下文
   */
  public ScrollViewGroup(Context context) {
    this(context, null);
  }

  /**
   * 在XML文件中使用的时候调用
   *
   * @param context 上下文
   * @param attrs  属性:如 android:layout_width="wrap_content"
   */
  public ScrollViewGroup(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  /**
   * 在xml文件中调用,并且使用了自定义属性的时候调用
   *
   * @param context   上下文
   * @param attrs    属性:如 android:layout_width="wrap_content"
   * @param defStyleAttr 自定义属性的id
   */
  public ScrollViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
  }

  /**
   * 初始化方法
   * 初始化滚动辅助类Scroller以及计算出屏幕宽度
   *
   * @param context 上下文
   */
  private void init(Context context) {
    //初始化辅助类
    mScroller = new Scroller(context);
    //获取屏幕宽度
    WindowManager manager = (WindowManager) context
        .getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics outMetrics = new DisplayMetrics();
    manager.getDefaultDisplay().getMetrics(outMetrics);
    screenWidth = outMetrics.widthPixels;
    //获取最小和最大的移动距离
    final ViewConfiguration configuration = ViewConfiguration.get(context);
    mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
    mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
  }

  /**
   * 滚动时需要重写的方法,用于控制滚动
   */
  @Override
  public void computeScroll() {
    //判断滚动时候停止
    if (mScroller.computeScrollOffset()) {
      //滚动到指定的位置
      scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
      //这句话必须写,否则不能实时刷新
      postInvalidate();
    }
  }

  /**
   * 手指触屏事件监听
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub
    int action = event.getAction();
    //获取现在手指所在的位置的x坐标
    float x = event.getX();
    //判断触发的时间
    switch (action) {
      //按下事件
      case MotionEvent.ACTION_DOWN:
        //初始化或服用加速度测试器
        initOrResetVelocityTracker();
        //测试器添加按下事件
        mVelocityTracker.addMovement(event);
        //如果停止滚动则取消动画(即手指按下就停止滚动)
        if (!mScroller.isFinished()) {
          mScroller.abortAnimation();
        }
        //获取现在的x坐标
        mLastMotionX = event.getX();
        break;
      //移动事件
      case MotionEvent.ACTION_MOVE:
        //测试器添加移动事件
        if (mVelocityTracker != null) {
          mVelocityTracker.addMovement(event);
        }
        //计算移动的偏移量
        float delt = mLastMotionX - x;
        //重置手指位置
        mLastMotionX = x;
        //滚动
        scrollBy((int) delt, 0);
        break;
      //手指抬起事件
      case MotionEvent.ACTION_UP:
        //测试器添加抬起事件
        mVelocityTracker.addMovement(event);
        //添加加速度的测试时间,这里是测量1000毫秒内的加速度
        mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
        //获取x方向加速度
        float pxsec = mVelocityTracker.getXVelocity();
        //得到最后一个子View
        View lastChild = getChildAt(getChildCount() - 1);
        //获取滑动的最大滑动距离(最后一个Child的右边框的坐标减去屏幕的宽度)
        int finalyChild = (int) (lastChild.getX() + lastChild.getWidth() - screenWidth);
        //如果x的加速度大于系统设定的最小移动距离,就可以惯性滑动
        if (Math.abs(pxsec) > mMinimumVelocity)
          mScroller.fling(getScrollX(), 0, (int) -pxsec, 0, 0, finalyChild, 0, 0);
        //如果滑动的距离小于第一个控件的最左边(0)则回弹至(0,0)点
        if (getScrollX() < 0) {
          scrollTo(0, 0);
        }
        //如果滑动的距离大于最大可滑动距离则滑动到最后一个子View
        if (getScrollX() >= finalyChild)
          scrollTo(finalyChild, 0);
        //刷新界面
        invalidate();
        //清空测试器
        recycleVelocityTracker();
        break;
      default:
        break;
    }

    return true;
  }

  /**
   * 创建或复用加速度测试器
   */
  private void initOrResetVelocityTracker() {
    if (mVelocityTracker == null) {
      mVelocityTracker = VelocityTracker.obtain();
    } else {
      mVelocityTracker.clear();
    }
  }

  /**
   * 回收加速度测试器,防止内存泄漏
   */
  private void recycleVelocityTracker() {
    if (mVelocityTracker != null) {
      mVelocityTracker.recycle();
      mVelocityTracker = null;
    }
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //重新设置宽高
    this.setMeasuredDimension(measureWidth(widthMeasureSpec, heightMeasureSpec), measureHeight(widthMeasureSpec, heightMeasureSpec));
  }

   /**
   * 测量宽度
   */
  private int measureWidth(int widthMeasureSpec, int heightMeasureSpec) {
    // 宽度
    int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
    int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
    //父控件的宽(wrap_content)
    int width = 0;
    int childCount = getChildCount();

    //重新测量子view的宽度,以及最大高度
    for (int i = 0; i < childCount; i++) {
      View child = getChildAt(i);
      measureChild(child, widthMeasureSpec, heightMeasureSpec);
      MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
      int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
      width += childWidth;
    }
    return modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width;
  }

  /**
   * 测量高度
   */
  private int measureHeight(int widthMeasureSpec, int heightMeasureSpec) {
    //高度
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
    int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
    //父控件的高(wrap_content)
    int height = 0;
    int childCount = getChildCount();

    //重新测量子view的宽度,以及最大高度
    for (int i = 0; i < childCount; i++) {
      View child = getChildAt(i);
      measureChild(child, widthMeasureSpec, heightMeasureSpec);
      MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
      int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
      height += childHeight;
    }
    height = height / childCount;
    return modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height;
  }

  /**
   * 给子布局设定位置
   */
  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int childLeft = 0;//子View左边的间距
    int childWidth;//子View的宽度
    int height = getHeight();//屏幕的宽度
    int childCount = getChildCount();//子View的数量
    for (int i = 0; i < childCount; i++) {
      View child = getChildAt(i);
      MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
      childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
      child.layout(childLeft, 0, childLeft + childWidth, height);
      childLeft += childWidth;
    }
  }

  @Override
  public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new MarginLayoutParams(getContext(), attrs);
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# Android  # viewgroup  # 滑动  # Android继承ViewGroup实现Scroll滑动效果的方法示例  # Android中实现可滑动的Tab的3种方式  # Android中实现监听ScrollView滑动事件  # android中使用Activity实现监听手指上下左右滑动  # android 通过向viewpage中添加listview来完成滑动效果(类似于qq滑动界面)  # Android中实现水平滑动(横向滑动)ListView示例  # 解析Android中实现滑动翻页之ViewFlipper的使用详解  # android开发教程之实现滑动关闭fragment示例  # Android利用ViewPager实现滑动广告板实例源码  # Android自定义ViewGroup实现弹性滑动效果  # 自定义  # 按下  # 第一个  # 这句话  # 上一  # 重写  # 大可  # 大家多多  # 计算出  # 清空  # 就可以  # 时需  # 复用  # 增加了  # 使用了  # 偏移量  # xml  # defStyleAttr  # id  # super 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel如何保护应用免受CSRF攻击?(原理和示例)  制作ppt免费网站有哪些,有哪些比较好的ppt模板下载网站?  Laravel数据库迁移怎么用_Laravel Migration管理数据库结构的正确姿势  PHP 500报错的快速解决方法  Python自然语言搜索引擎项目教程_倒排索引查询优化案例  如何用AI帮你把自己的生活经历写成一个有趣的故事?  Laravel如何使用.env文件管理环境变量?(最佳实践)  Win11应用商店下载慢怎么办 Win11更改DNS提速下载【修复】  Edge浏览器怎么启用睡眠标签页_节省电脑内存占用优化技巧  详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)  动图在线制作网站有哪些,滑动动图图集怎么做?  javascript中数组(Array)对象和字符串(String)对象的常用方法总结  JavaScript如何实现类型判断_typeof和instanceof有什么区别  ,怎么在广州志愿者网站注册?  php打包exe后无法访问网络共享_共享权限设置方法【教程】  怎么用AI帮你设计一套个性化的手机App图标?  宙斯浏览器视频悬浮窗怎么开启 边看视频边操作其他应用教程  如何在搬瓦工VPS快速搭建网站?  javascript读取文本节点方法小结  如何制作一个表白网站视频,关于勇敢表白的小标题?  Laravel如何发送邮件_Laravel Mailables构建与发送邮件的简明教程  Laravel怎么实现验证码功能_Laravel集成验证码库防止机器人注册  深圳网站制作设计招聘,关于服装设计的流行趋势,哪里的资料比较全面?  移动端手机网站制作软件,掌上时代,移动端网站的谷歌SEO该如何做?  iOS中将个别页面强制横屏其他页面竖屏  浅析上传头像示例及其注意事项  Laravel怎么生成二维码图片_Laravel集成Simple-QrCode扩展包与参数设置【实战】  如何在香港服务器上快速搭建免备案网站?  香港服务器建站指南:免备案优势与SEO优化技巧全解析  北京企业网站设计制作公司,北京铁路集团官方网站?  香港服务器如何优化才能显著提升网站加载速度?  在Oracle关闭情况下如何修改spfile的参数  CSS3怎么给轮播图加过渡动画_transition加transform实现【技巧】  公司网站制作需要多少钱,找人做公司网站需要多少钱?  Laravel怎么实现前端Toast弹窗提示_Laravel Session闪存数据Flash传递给前端【方法】  Laravel Fortify是什么,和Jetstream有什么关系  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  绝密ChatGPT指令:手把手教你生成HR无法拒绝的求职信  Laravel怎么实现验证码(Captcha)功能  昵图网官网入口 昵图网素材平台官方入口  香港服务器网站生成指南:免费资源整合与高速稳定配置方案  Win11搜索栏无法输入_解决Win11开始菜单搜索没反应问题【技巧】  Laravel怎么实现支付功能_Laravel集成支付宝微信支付  JS实现鼠标移上去显示图片或微信二维码  Laravel中的Facade(门面)到底是什么原理  Win11搜索不到蓝牙耳机怎么办 Win11蓝牙驱动更新修复【详解】  Laravel中间件如何使用_Laravel自定义中间件实现权限控制  Python图片处理进阶教程_Pillow滤镜与图像增强  网页设计与网站制作内容,怎样注册网站?  如何在万网开始建站?分步指南解析