热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

超好看的下拉刷新动画Android代码实现

超好看的下拉刷新动画Android代码实现,效果简单大方,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近看到了好多高端、大气、上档次的动画效果,如果给你的项目中加上这些动画,相信你的app一定很优秀,今天给大家分析一下来自Yalantis的一个超好看的下拉刷新动画。

首先我们看一下效果如何:

怎么样?是不是很高大上?接下来我们看一下代码:

一、首先我们需要自定义刷新的动态RefreshView(也就是下拉时候的头)
1.初始化头所占用的Dimens

private void initiateDimens() { 
    mScreenWidth = mContext.getResources().getDisplayMetrics().widthPixels; 
    mJetTopOffset = mParent.getTotalDragDistance() * 0.5f; 
    mTop = -mParent.getTotalDragDistance(); 
  } 

2.为头填充图片,设置图片的大小
分别为左边的云彩,右边的云彩,中间的云彩还有中间的飞机,飞机是带有动画的,下面会介绍飞机的动画

private void createBitmaps() { 
    mLeftClouds = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.clouds_left); 
    mRightClouds = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.clouds_right); 
    mFrOntClouds= BitmapFactory.decodeResource(mContext.getResources(), R.drawable.clouds_center); 
    mJet = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.airplane); 
 
    mJetWidthCenter = mJet.getWidth() / 2; 
    mJetHeightCenter = mJet.getHeight() / 2; 
    mFrOntCloudWidthCenter= mFrontClouds.getWidth() / 2; 
    mFrOntCloudHeightCenter= mFrontClouds.getHeight() / 2; 
 
    mRightCloudsWidthCenter = mRightClouds.getWidth() / 2; 
    mRightCloudsHeightCenter = mRightClouds.getHeight() / 2; 
    mLeftCloudsWidthCenter = mLeftClouds.getWidth() / 2; 
    mLeftCloudsHeightCenter = mLeftClouds.getHeight() / 2; 
  } 

3.然后我们来画这个头

public void draw(@NonNull Canvas canvas) { 
    final int saveCount = canvas.save(); 
 
    // DRAW BACKGROUND. 
    canvas.drawColor(mContext.getResources().getColor(R.color.sky_background)); 
 
    if (isRefreshing) { 
      // Set up new set of wind 
      while (mWinds.size()  1) { 
          y = 0; 
          while (y == 0) { 
            float tmp = (float) (mParent.getTotalDragDistance() / (Math.random() * RANDOM_Y_COEFFICIENT)); 
 
            for (Map.Entry wind : mWinds.entrySet()) { 
              // We want that interval will be greater than fifth part of draggable distance 
              if (Math.abs(wind.getKey() - tmp) > mParent.getTotalDragDistance() / RANDOM_Y_COEFFICIENT) { 
                y = tmp; 
              } else { 
                y = 0; 
                break; 
              } 
            } 
          } 
        } 
 
        mWinds.put(y, x); 
        drawWind(canvas, y, x); 
      } 
 
      // Draw current set of wind 
      if (mWinds.size() >= WIND_SET_AMOUNT) { 
        for (Map.Entry wind : mWinds.entrySet()) { 
          drawWind(canvas, wind.getKey(), wind.getValue()); 
        } 
      } 
 
      // We should to create new set of winds 
      if (mInverseDirection && mNewWindSet) { 
        mWinds.clear(); 
        mNewWindSet = false; 
        mWindLineWidth = random(MIN_WIND_LINE_WIDTH, MAX_WIND_LINE_WIDTH); 
      } 
 
      // needed for checking direction 
      mLastAnimatiOnTime= mLoadingAnimationTime; 
    } 
 
    drawJet(canvas); 
    drawSideClouds(canvas); 
    drawCenterClouds(canvas); 
 
    canvas.restoreToCount(saveCount); 
  } 
/** 
   * Draw wind on loading animation 
   * 
   * @param canvas - area where we will draw 
   * @param y    - y position fot one of lines 
   * @param xOffset - x offset for on of lines 
   */ 
  private void drawWind(Canvas canvas, float y, float xOffset) { 
    /* We should multiply current animation time with this coefficient for taking all screen width in time 
    Removing slowing of animation with dividing on {@LINK #SLOW_DOWN_ANIMATION_COEFFICIENT} 
    And we should don't forget about distance that should "fly" line that depend on screen of device and x offset 
    */ 
    float cof = (mScreenWidth + xOffset) / (LOADING_ANIMATION_COEFFICIENT / SLOW_DOWN_ANIMATION_COEFFICIENT); 
    float time = mLoadingAnimationTime; 
 
    // HORRIBLE HACK FOR REVERS ANIMATION THAT SHOULD WORK LIKE RESTART ANIMATION 
    if (mLastAnimationTime - mLoadingAnimationTime > 0) { 
      mInverseDirection = true; 
      // take time from 0 to end of animation time 
      time = (LOADING_ANIMATION_COEFFICIENT / SLOW_DOWN_ANIMATION_COEFFICIENT) - mLoadingAnimationTime; 
    } else { 
      mNewWindSet = true; 
      mInverseDirection = false; 
    } 
 
    // Taking current x position of drawing wind 
    // For fully disappearing of line we should subtract wind line width 
    float x = (mScreenWidth - (time * cof)) + xOffset - mWindLineWidth; 
    float xEnd = x + mWindLineWidth; 
 
    canvas.drawLine(x, y, xEnd, y, mWindPaint); 
  } 
 
  private void drawSideClouds(Canvas canvas) { 
    Matrix matrixLeftClouds = mMatrix; 
    Matrix matrixRightClouds = mAdditionalMatrix; 
    matrixLeftClouds.reset(); 
    matrixRightClouds.reset(); 
 
    // Drag percent will newer get more then 1 here 
    float dragPercent = Math.min(1f, Math.abs(mPercent)); 
 
    boolean overdrag = false; 
 
    // But we check here for overdrag 
    if (mPercent > 1.0f) { 
      overdrag = true; 
    } 
 
    float scale; 
    float scalePercentDelta = dragPercent - SCALE_START_PERCENT; 
    if (scalePercentDelta > 0) { 
      float scalePercent = scalePercentDelta / (1.0f - SCALE_START_PERCENT); 
      scale = SIDE_CLOUDS_INITIAL_SCALE + (SIDE_CLOUDS_FINAL_SCALE - SIDE_CLOUDS_INITIAL_SCALE) * scalePercent; 
    } else { 
      scale = SIDE_CLOUDS_INITIAL_SCALE; 
    } 
 
    // Current y position of clouds 
    float dragYOffset = mParent.getTotalDragDistance() * (1.0f - dragPercent); 
 
    // Position where clouds fully visible on screen and we should drag them with content of listView 
    int cloudsVisiblePosition = mParent.getTotalDragDistance() / 2 - mLeftCloudsHeightCenter; 
 
    boolean needMoveCloudsWithCOntent= false; 
    if (dragYOffset  1.0f) { 
      overdrag = true; 
      // Here we want know about how mach percent of over drag we done 
      overdragPercent = Math.abs(1.0f - mPercent); 
    } 
 
    float scalePercentDelta = dragPercent - SCALE_START_PERCENT; 
    if (scalePercentDelta > 0) { 
      float scalePercent = scalePercentDelta / (1.0f - SCALE_START_PERCENT); 
      scale = CENTER_CLOUDS_INITIAL_SCALE + (CENTER_CLOUDS_FINAL_SCALE - CENTER_CLOUDS_INITIAL_SCALE) * scalePercent; 
    } else { 
      scale = CENTER_CLOUDS_INITIAL_SCALE; 
    } 
 
    float parallaxPercent = 0; 
    boolean parallax = false; 
    // Current y position of clouds 
    float dragYOffset = mParent.getTotalDragDistance() * dragPercent; 
    // Position when should start parallax scrolling 
    int startParallaxHeight = mParent.getTotalDragDistance() - mFrontCloudHeightCenter; 
 
    if (dragYOffset > startParallaxHeight) { 
      parallax = true; 
      parallaxPercent = dragYOffset - startParallaxHeight; 
    } 
 
    float offsetX = (mScreenWidth / 2) - mFrontCloudWidthCenter; 
    float offsetY = dragYOffset 
        - (parallax ? mFrontCloudHeightCenter + parallaxPercent : mFrontCloudHeightCenter) 
        + (overdrag ? mTop : 0); 
 
    float sx = overdrag ? scale + overdragPercent / 4 : scale; 
    float sy = overdrag ? scale + overdragPercent / 2 : scale; 
 
    if (isRefreshing && !overdrag) { 
      if (checkCurrentAnimationPart(AnimationPart.FIRST)) { 
        sx = scale - (getAnimationPartValue(AnimationPart.FIRST) / LOADING_ANIMATION_COEFFICIENT) / 8; 
      } else if (checkCurrentAnimationPart(AnimationPart.SECOND)) { 
        sx = scale - (getAnimationPartValue(AnimationPart.SECOND) / LOADING_ANIMATION_COEFFICIENT) / 8; 
      } else if (checkCurrentAnimationPart(AnimationPart.THIRD)) { 
        sx = scale + (getAnimationPartValue(AnimationPart.THIRD) / LOADING_ANIMATION_COEFFICIENT) / 6; 
      } else if (checkCurrentAnimationPart(AnimationPart.FOURTH)) { 
        sx = scale + (getAnimationPartValue(AnimationPart.FOURTH) / LOADING_ANIMATION_COEFFICIENT) / 6; 
      } 
      sy = sx; 
    } 
 
    matrix.postScale(sx, sy, mFrontCloudWidthCenter, mFrontCloudHeightCenter); 
    matrix.postTranslate(offsetX, offsetY); 
 
    canvas.drawBitmap(mFrontClouds, matrix, null); 
  } 
 
  private void drawJet(Canvas canvas) { 
    Matrix matrix = mMatrix; 
    matrix.reset(); 
 
    float dragPercent = mPercent; 
    float rotateAngle = 0; 
 
    // Check overdrag 
    if (dragPercent > 1.0f && !mEndOfRefreshing) { 
      rotateAngle = (dragPercent % 1) * 10; 
      dragPercent = 1.0f; 
    } 
 
    float offsetX = ((mScreenWidth * dragPercent) / 2) - mJetWidthCenter; 
 
    float offsetY = mJetTopOffset 
        + (mParent.getTotalDragDistance() / 2) 
        * (1.0f - dragPercent) 
        - mJetHeightCenter; 
 
    if (isRefreshing) { 
      if (checkCurrentAnimationPart(AnimationPart.FIRST)) { 
        offsetY -= getAnimationPartValue(AnimationPart.FIRST); 
      } else if (checkCurrentAnimationPart(AnimationPart.SECOND)) { 
        offsetY -= getAnimationPartValue(AnimationPart.SECOND); 
      } else if (checkCurrentAnimationPart(AnimationPart.THIRD)) { 
        offsetY += getAnimationPartValue(AnimationPart.THIRD); 
      } else if (checkCurrentAnimationPart(AnimationPart.FOURTH)) { 
        offsetY += getAnimationPartValue(AnimationPart.FOURTH); 
      } 
    } 
 
    matrix.setTranslate(offsetX, offsetY); 
 
    if (dragPercent == 1.0f) { 
      matrix.preRotate(rotateAngle, mJetWidthCenter, mJetHeightCenter); 
    } 
 
    canvas.drawBitmap(mJet, matrix, null); 
  } 

动画效果已经画好了,下面我们来看看怎么结合下拉刷新来调用吧?
二、我们还需要自定义一个PullToRefreshView(下拉刷新)
1.我们的PullToRefreshView这里需要继承ViewGroup
我们先把刚才定义的刷新时的动画加进来

private RefreshView mRefreshView; 
private ImageView mRefreshImageView; 
mRefreshImageView = new ImageView(context); 
    mRefreshView = new RefreshView(getContext(), this); 
    mRefreshImageView.setImageDrawable(mRefreshView); 
 
    addView(mRefreshImageView); 

2.然后我们设置OntouchEvent()事件

@Override 
  public boolean onTouchEvent(@NonNull MotionEvent ev) { 
 
    if (!mIsBeingDragged) { 
      return super.onTouchEvent(ev); 
    } 
 
    final int action = MotionEventCompat.getActionMasked(ev); 
 
    switch (action) { 
      case MotionEvent.ACTION_MOVE: { 
        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 
        if (pointerIndex <0) { 
          return false; 
        } 
 
        final float y = MotionEventCompat.getY(ev, pointerIndex); 
        final float yDiff = y - mInitialMotionY; 
        final float scrollTop = yDiff * DRAG_RATE; 
        mCurrentDragPercent = scrollTop / mTotalDragDistance; 
        if (mCurrentDragPercent <0) { 
          return false; 
        } 
        float boundedDragPercent = Math.min(1f, Math.abs(mCurrentDragPercent)); 
        float extraOS = Math.abs(scrollTop) - mTotalDragDistance; 
        float slingshotDist = mTotalDragDistance; 
        float tensiOnSlingshotPercent= Math.max(0, 
            Math.min(extraOS, slingshotDist * 2) / slingshotDist); 
        float tensiOnPercent= (float) ((tensionSlingshotPercent / 4) - Math.pow( 
            (tensionSlingshotPercent / 4), 2)) * 2f; 
        float extraMove = (slingshotDist) * tensionPercent / 2; 
        int targetY = (int) ((slingshotDist * boundedDragPercent) + extraMove); 
 
        mRefreshView.setPercent(mCurrentDragPercent); 
        setTargetOffsetTop(targetY - mCurrentOffsetTop, true); 
        break; 
      } 
      case MotionEventCompat.ACTION_POINTER_DOWN: 
        final int index = MotionEventCompat.getActionIndex(ev); 
        mActivePointerId = MotionEventCompat.getPointerId(ev, index); 
        break; 
      case MotionEventCompat.ACTION_POINTER_UP: 
        onSecondaryPointerUp(ev); 
        break; 
      case MotionEvent.ACTION_UP: 
      case MotionEvent.ACTION_CANCEL: { 
        if (mActivePointerId == INVALID_POINTER) { 
          return false; 
        } 
        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 
        final float y = MotionEventCompat.getY(ev, pointerIndex); 
        final float overScrollTop = (y - mInitialMotionY) * DRAG_RATE; 
        mIsBeingDragged = false; 
        if (overScrollTop > mTotalDragDistance) { 
          setRefreshing(true, true); 
        } else { 
          mRefreshing = false; 
          animateOffsetToPosition(mAnimateToStartPosition); 
        } 
        mActivePointerId = INVALID_POINTER; 
        return false; 
      } 
    } 
 
    return true; 
  } 

三、最后我们看怎样在Activity中使用这个下拉刷新控件
1.先看一下布局文件
这里是我们的下拉刷新空间嵌套着我们的ListView,然后我们再给ListView填充数据即可

 
 
   
 
     
 
   
 
 

2.为ListView填充数据
为了我们的效果比较好看,这里我们给ListView的每一个item填充不同的颜色,看起来会比较高大上。

Map map; 
    List> sampleList = new ArrayList>(); 
 
 
    int[] colors = { 
        R.color.saffron, 
        R.color.eggplant, 
        R.color.sienna}; 
 
    int[] tripNames = { 
        R.string.trip_to_india, 
        R.string.trip_to_italy, 
        R.string.trip_to_indonesia}; 
 
    for (int i = 0; i (); 
      map.put(SampleAdapter.KEY_NAME, tripNames[i]); 
      map.put(SampleAdapter.KEY_COLOR, colors[i]); 
      sampleList.add(map); 
    } 
 
    ListView listView = (ListView) findViewById(R.id.list_view); 
    listView.setAdapter(new SampleAdapter(this, R.layout.list_item, sampleList)); 

3.最后,我们再设置一下下拉刷新的监听事件就OK了

mPullToRefreshView = (PullToRefreshView) findViewById(R.id.pull_to_refresh); 
    mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() { 
      @Override 
      public void onRefresh() { 
        mPullToRefreshView.postDelayed(new Runnable() { 
          @Override 
          public void run() { 
            mPullToRefreshView.setRefreshing(false); 
          } 
        }, REFRESH_DELAY); 
      } 
    }); 

怎么样?有没有很高大上啊?

大家可以动手实践一下,希望对大家的学习有所帮助。


推荐阅读
  • BeautifulSoup4 是一个功能强大的HTML和XML解析库,它能够帮助开发者轻松地从网页中提取信息。本文将介绍BeautifulSoup4的基本功能、安装方法、与其他解析工具的对比以及简单的使用示例。 ... [详细]
  • 本教程旨在指导开发者如何在Android应用中通过ViewPager组件实现图片轮播功能,适用于初学者和有一定经验的开发者,帮助提升应用的视觉吸引力。 ... [详细]
  • 在Android应用开发中,当在MenuItem中通过app:actionLayout属性使用Switch控件时,可能会遇到空指针异常的问题。本文将探讨该问题的原因及解决方案。 ... [详细]
  • 本文介绍了如何使用Maven命令对Spring Boot项目中的子模块进行独立打包,包括依赖树的查看、项目的运行和打包等基本操作。 ... [详细]
  • 本文探讨了 Boost 库中的 Program Options 组件,这是一个强大的工具,用于解析命令行参数和配置文件。文章介绍了如何正确设置和使用该组件,包括处理复杂选项和负数值的方法。 ... [详细]
  • 本文通过具体示例详细介绍了 Python 中的装饰器和装饰类的使用方法,包括带参数的装饰器和装饰类的应用场景。 ... [详细]
  • 解决 Pytest 运行时出现 FileNotFoundError 的方法
    在使用 Pytest 进行测试时,可能会遇到 FileNotFoundError 错误,提示无法找到指定的文件或目录。本文将探讨该错误的原因及解决方案。 ... [详细]
  • HDU1085 捕获本·拉登!
    问题描述众所周知,本·拉登是一位臭名昭著的恐怖分子,他已失踪多年。但最近有报道称,他藏匿在中国杭州!虽然他躲在杭州的一个洞穴中不敢外出,但近年来他因无聊而沉迷于数学问题,并声称如果有人能解出他的题目,他就自首。 ... [详细]
  • SpringBoot新手入门指南
    本文旨在为初次接触SpringBoot的开发者提供一份详细的入门指导,包括如何快速搭建并运行一个简单的SpringBoot应用。通过本文,读者将了解Maven项目的构建、必要的配置文件设置以及基本的应用开发流程。 ... [详细]
  • 本视频详细介绍了如何利用J2EE、JBPM 3.x/4.3、Flex流程设计器、jQuery以及授权认证机制构建高效的企业普及版贝斯OA及工作流管理系统。 ... [详细]
  • BL550721、特点液晶驱动输出:Common输出4线,Segment输出36线内置显示寄存器364144bit2线串行接口(SCL,SDA)内置震荡电路内置液晶驱动电源电路13 ... [详细]
  • 本文介绍了如何在Windows操作系统中安装FFTW库,并详细说明了使用Visual Studio 2010进行4096点快速傅里叶变换(FFT)的步骤。包括下载预编译文件、生成库文件以及配置环境等关键环节。 ... [详细]
  • javascript——对象的概念——函数 1 (函数对象的属性和方法)
    一、创建函数函数是一种对象:Function类是对象,可以通过Function实例化一个函数,不过最多的还是利用function来创建函数。方式一:利用Function类来实例化函 ... [详细]
  • 在开发H5页面时,为了减少资源请求和简化工作流程,直接使用SVG和CSS3来创建简单的图形元素是一个高效的选择。本文将探讨如何不依赖于第三方图标库,仅通过HTML和CSS技术实现一个‘返回顶部’的图标。 ... [详细]
  • IEC60825激光产品安全标准详解
    随着激光技术在全球范围内的广泛应用,尤其是激光投影显示技术的兴起,了解和遵守相关的安全标准变得尤为重要。本文将详细介绍IEC60825激光产品安全标准及其重要性。 ... [详细]
author-avatar
幸福的小馋豆
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有