快速仿写京东、天猫下拉刷新

fangcao 7年前
   <p>好久没输出文章了,最近研发任务比较忙,果然计划赶不上变化,之前还希望能一周一输出,好吧,我还是承认自己比较懒好了,=.=## 这次跟大家分享一下下拉刷新,之前我们的公司的项目一直都是使用SwipeRefreshLayout,官方的Md风格,好用少Bug。闲话不多说了,咱们现在分析一下哪种下拉刷新比较多,有的是直接包在ListView或者RecyclerView的头部,有得则是像SwipeRefreshLayout一样,包在视图的最外层,个人建议使用包在最外层的做法,可扩展性比较强,另一种的话,可以借鉴一下XRecyclerView,具体的就不多说了,咱们使用最外层的方法,快速的构建一个类似像京东、天猫的下拉刷新。</p>    <p>1.使用框架android-Ultra-Pull-To-Refresh</p>    <p>大家感兴趣的可以去看一下这个下拉刷新框架,非常强大,可扩展性非常强,兼容各种view的下拉刷新事件。</p>    <p>2.京东下拉刷新</p>    <p>先放一张效果来看一下,京东的下拉刷新动画:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/1232a35da84b82258bf196d58afb4939.gif"></p>    <p style="text-align:center">jd_origin.gif</p>    <p>通俗的来说,就是一个快递小哥,跑过来,接住商品,然后刷新的时候,自己拿着商品跑起来。(解释有点牵强啊)</p>    <p>咱们来分析一下整一个过程:</p>    <p>1.快递小哥从远处跑过去拿商品,可以拆成两个部分.</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/3101d5f06de6ffd0db95f3ceae290545.png"></p>    <p style="text-align:center">Paste_Image.png</p>    <p>当拿到商品之后,就跑起来,在我们程序里,就是动画:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/d3d5ebbc0d63ac5696ff8ad8c889a5dd.png"></p>    <p style="text-align:center">Paste_Image.png</p>    <p>(你去解压一下京东的apk,你也能拿到这些图片)</p>    <p>其实就是图片之间的切换,以上的准备工作都完成了,看看这个xml应该怎么写:</p>    <pre>  <code class="language-java"><?xml version="1.0" encoding="utf-8"?>  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="wrap_content">          <FrameLayout          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_toLeftOf="@+id/layout_tx">            <ImageView              android:id="@+id/iv_man"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:background="@mipmap/a2a" />            <ImageView              android:id="@+id/iv_goods"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_gravity="right|center"              android:src="@mipmap/a29" />      </FrameLayout>        <LinearLayout          android:id="@+id/layout_tx"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_centerInParent="true"          android:layout_marginLeft="5dp"          android:gravity="center_vertical"          android:orientation="vertical"          android:padding="5dp">            <TextView              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="让购物更便捷"              android:textSize="14sp" />            <TextView              android:id="@+id/tv_remain"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:layout_marginTop="5dp"              android:text="松开刷新"              android:textSize="12sp" />      </LinearLayout>      </RelativeLayout></code></pre>    <p>根据第一个人跟商品,咱们先分开两个ImageView,使用FrameLayout布局,然后让这两个ImageView放进去,商品的这个ImageView设置layoutgravity=right.</p>    <p>咱们再看看android-Ultra-Pull-To-Refresh这个框架给我们带来什么。</p>    <pre>  <code class="language-java">public interface PtrUIHandler {        /**       * When the content view has reached top and refresh has been completed, view will be reset.       *       * @param frame       */      public void onUIReset(PtrFrameLayout frame);        /**       * prepare for loading       *       * @param frame       */      public void onUIRefreshPrepare(PtrFrameLayout frame);        /**       * perform refreshing UI       */      public void onUIRefreshBegin(PtrFrameLayout frame);        /**       * perform UI after refresh       */      public void onUIRefreshComplete(PtrFrameLayout frame);        public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator);  }</code></pre>    <p>这是一下下拉刷新事件的接口,只要实现以上接口就能得到相应的,得到以上接口</p>    <p>至于各个接口有什么,看接口名大家应该就知道了。</p>    <p>直接贴代码更直观:</p>    <pre>  <code class="language-java">/**   * 下拉刷新header   * Created by shenminjie on 2016/12/6.   */  public class JdRefreshHeader extends FrameLayout implements PtrUIHandler {        /**       * 提醒文本       */      private TextView mTvRemind;        /**       * 快递员logo       */      private ImageView mIvMan;        /**       * 商品logo       */      private ImageView mIvGoods;        /**       * 状态识别       */      private int mState;        /**       * 重置       * 准备刷新       * 开始刷新       * 结束刷新       */      public static final int STATE_RESET = -1;      public static final int STATE_PREPARE = 0;      public static final int STATE_BEGIN = 1;      public static final int STATE_FINISH = 2;        public static final int MARGIN_RIGHT = 100;        /**       * 动画       */      private AnimationDrawable mAnimation;          public JdRefreshHeader(Context context) {          super(context);          initView();      }        public JdRefreshHeader(Context context, AttributeSet attrs) {          super(context, attrs);          initView();      }        public JdRefreshHeader(Context context, AttributeSet attrs, int defStyleAttr) {          super(context, attrs, defStyleAttr);          initView();      }        /**       * 初始化view       */      private void initView() {          View view = LayoutInflater.from(getContext()).inflate(R.layout.jd_refresh_header_view, this, false);          mTvRemind = (TextView) view.findViewById(R.id.tv_remain);          mIvMan = (ImageView) view.findViewById(R.id.iv_man);          mIvGoods = (ImageView) view.findViewById(R.id.iv_goods);          addView(view);        }          @Override      public void onUIReset(PtrFrameLayout frame) {          mState = STATE_RESET;      }        @Override      public void onUIRefreshPrepare(PtrFrameLayout frame) {          mState = STATE_PREPARE;      }        @Override      public void onUIRefreshBegin(PtrFrameLayout frame) {          mState = STATE_BEGIN;          //隐藏商品logo,开启跑步动画          mIvGoods.setVisibility(View.GONE);          mIvMan.setBackgroundResource(R.drawable.runningman);          mAnimation = (AnimationDrawable) mIvMan.getBackground();          if (!mAnimation.isRunning()) {              mAnimation.start();          }      }        @Override      public void onUIRefreshComplete(PtrFrameLayout frame) {          mState = STATE_FINISH;          mIvGoods.setVisibility(View.VISIBLE);          //停止动画          if (mAnimation.isRunning()) {              mAnimation.stop();          }          mIvMan.setBackgroundResource(R.mipmap.a2a);      }        @Override      public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {          //处理提醒字体          switch (mState) {              case STATE_PREPARE:                  //logo设置                  mIvMan.setAlpha(ptrIndicator.getCurrentPercent());                  mIvGoods.setAlpha(ptrIndicator.getCurrentPercent());                  FrameLayout.LayoutParams mIvManLayoutParams = (LayoutParams) mIvMan.getLayoutParams();                  if (ptrIndicator.getCurrentPercent() <= 1) {                      mIvMan.setScaleX(ptrIndicator.getCurrentPercent());                      mIvMan.setScaleY(ptrIndicator.getCurrentPercent());                      mIvGoods.setScaleX(ptrIndicator.getCurrentPercent());                      mIvGoods.setScaleY(ptrIndicator.getCurrentPercent());                      int marginRight = (int) (MARGIN_RIGHT - MARGIN_RIGHT * ptrIndicator.getCurrentPercent());                      mIvManLayoutParams.setMargins(0, 0, marginRight, 0);                      mIvMan.setLayoutParams(mIvManLayoutParams);                  }                  if (ptrIndicator.getCurrentPercent() < 1.2) {                      mTvRemind.setText("下拉刷新...");                  } else {                      mTvRemind.setText("松开刷新...");                  }                  break;              case STATE_BEGIN:                  mTvRemind.setText("更新中...");                  break;              case STATE_FINISH:                  mTvRemind.setText("加载完成...");                  break;          }      }  }</code></pre>    <p>创建一个成员变量mState,用于保存下拉刷新的时候,每一个状态,然后根据保存好的状态在UiPositionChange的接口中,对UI进行相应的修改,保存每个状态文本的提示,在下拉的过程中,通过UiPositionChange的回调,获取PtrIndicator中,可以获取下拉的百分比,根据这个百分比我们可以做很多东西,例如京东的快递小哥从远处跑过来拿商品,以及快递小哥与商品之间的大小,都可以根据这个PtrIndicator百分比进行设置其大小的比例,跑过来这个过程我使用的方法是利用marginRight进行设置两者之间的距离,当达到下拉刷新的临界点时,快递小哥跟商品之间的margin为0,达到了快递小哥获取商品的效果,然后当刷新的时候,隐藏商品,使用之前所提供的三张图片进行效应的切换,也就是动画:</p>    <pre>  <code class="language-java"><animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">      <item          android:drawable="@mipmap/a2b"          android:duration="70" />      <item          android:drawable="@mipmap/a2c"          android:duration="70" />      <item          android:drawable="@mipmap/a2d"          android:duration="70" />  </animation-list></code></pre>    <pre>  <code class="language-java">@Override  public void onUIRefreshBegin(PtrFrameLayout frame) {      mState = STATE_BEGIN;      //隐藏商品logo,开启跑步动画      mIvGoods.setVisibility(View.GONE);      mIvMan.setBackgroundResource(R.drawable.runningman);      mAnimation = (AnimationDrawable) mIvMan.getBackground();      if (!mAnimation.isRunning()) {          mAnimation.start();      }  }</code></pre>    <p>当刷新结束的时候,我们把动画停止,并把之前的商品显示出来:</p>    <pre>  <code class="language-java">@Override  public void onUIRefreshComplete(PtrFrameLayout frame) {      mState = STATE_FINISH;      mIvGoods.setVisibility(View.VISIBLE);      //停止动画      if (mAnimation.isRunning()) {          mAnimation.stop();      }      mIvMan.setBackgroundResource(R.mipmap.a2a);  }</code></pre>    <p>很简单,基本上难点框架都已经帮我们封装好了,我们只要继承PtrFrameLayout,添加相应的Header以及实现PtrUIHandler就可以实现。</p>    <pre>  <code class="language-java">/**   *仿京东下拉刷新   * Created by shenminjie on 2016/12/6.   */    public class JdRefreshLayout extends PtrFrameLayout {        /**       * headerView       */       JdRefreshHeader mHeaderView;        public JdRefreshLayout(Context context) {          super(context);          initView();      }        public JdRefreshLayout(Context context, AttributeSet attrs) {          super(context, attrs);          initView();      }        public JdRefreshLayout(Context context, AttributeSet attrs, int defStyle) {          super(context, attrs, defStyle);          initView();      }          /**       * 初始化view       */      private void initView() {          mHeaderView = new JdRefreshHeader(getContext());          setHeaderView(mHeaderView);          addPtrUIHandler(mHeaderView);      }      }</code></pre>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0d027dc0d3ac566b092bccaef5a3b473.gif"></p>    <p style="text-align:center">my_jd.gif</p>    <p>2、天猫</p>    <p>天猫的更简单,毫无动画可言,说白了就是个GIF,大家可以去下载个apk,解压后能得到其gif。</p>    <p>原理跟之前的是一样,但这里我使用的是fresco进行加载gif,方法有很多,大家感兴趣的可以去试试。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/cd50d61586b87a3e83100372349a95f9.gif"></p>    <p style="text-align:center">tmall_origin.gif</p>    <pre>  <code class="language-java">/**   * 下拉刷新header   * Created by shenminjie on 2016/12/6.   */  public class TmallRefreshHeader extends FrameLayout implements PtrUIHandler {        /**       * 提醒文本       */      private TextView mTvRemind;          /**       * 状态识别       */      private int mState;        /**       * 重置       * 准备刷新       * 开始刷新       * 结束刷新       */      public static final int STATE_RESET = -1;      public static final int STATE_PREPARE = 0;      public static final int STATE_BEGIN = 1;      public static final int STATE_FINISH = 2;          public TmallRefreshHeader(Context context) {          super(context);          initView();      }        public TmallRefreshHeader(Context context, AttributeSet attrs) {          super(context, attrs);          initView();      }        public TmallRefreshHeader(Context context, AttributeSet attrs, int defStyleAttr) {          super(context, attrs, defStyleAttr);          initView();      }        /**       * 初始化view       */      private void initView() {          View view = LayoutInflater.from(getContext()).inflate(R.layout.tmall_refresh_header_view, this, false);          mTvRemind = (TextView) view.findViewById(R.id.tv_remind);          SimpleDraweeView sdv = (SimpleDraweeView) view.findViewById(R.id.tm_logo);          DraweeController mDraweeController = Fresco.newDraweeControllerBuilder()                  .setAutoPlayAnimations(true)                  //设置uri,加载本地的gif资源                  .setUri(Uri.parse("res://" + getContext().getPackageName() + "/" + R.drawable.tm_mui_bike))//设置uri                  .build();          sdv.setController(mDraweeController);          addView(view);      }          @Override      public void onUIReset(PtrFrameLayout frame) {          mState = STATE_RESET;      }        @Override      public void onUIRefreshPrepare(PtrFrameLayout frame) {          mState = STATE_PREPARE;      }        @Override      public void onUIRefreshBegin(PtrFrameLayout frame) {          mState = STATE_BEGIN;      }        @Override      public void onUIRefreshComplete(PtrFrameLayout frame) {          mState = STATE_FINISH;      }        @Override      public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {          //处理提醒字体          switch (mState) {              case STATE_PREPARE:                  if (ptrIndicator.getCurrentPercent() < 1) {                      mTvRemind.setText("下拉刷新");                  } else {                      mTvRemind.setText("松开立即刷新");                  }                  break;              case STATE_BEGIN:                  mTvRemind.setText("正在刷新...");                  break;              case STATE_FINISH:                  mTvRemind.setText("加载完成...");                  break;          }      }  }    /**   * 仿天猫下拉刷新view   * Created by shenminjie on 2016/12/6.   */    public class TmallRefreshLayout extends PtrFrameLayout {        /**       * headerView       */       TmallRefreshHeader mHeaderView;        public TmallRefreshLayout(Context context) {          super(context);          initView();      }        public TmallRefreshLayout(Context context, AttributeSet attrs) {          super(context, attrs);          initView();      }        public TmallRefreshLayout(Context context, AttributeSet attrs, int defStyle) {          super(context, attrs, defStyle);          initView();      }          /**       * 初始化view       */      private void initView() {          mHeaderView = new TmallRefreshHeader(getContext());          setHeaderView(mHeaderView);          addPtrUIHandler(mHeaderView);      }      }</code></pre>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9a7a76ae99e897bd41d87cebb83b5fcf.gif"></p>    <p style="text-align:center">my_tmall.gif</p>    <p> </p>    <p> </p>    <p> </p>    <p> </p>