我想親手做一個刷新加載控件

其實很久以前就想自己實現(xiàn)一個下拉刷新上拉加載控件,之前一直用的是開源的控件,從一開始的PullToRefreshView到后來的SwipeRefreshLayout。雖然功能上都能實現(xiàn),但用別人的總感覺不得勁??吹絼e的app上用的炫酷的刷新加載控件就是心癢癢。

1.美團的是這樣的

美團.jpg
美團.jpg

2.京東的是這樣的

S61028-162146.jpg

3.新浪微博的是這樣的

微博.jpg
微博.jpg

看著都挺炫酷的,那咱們是不是也可以搞一個。既然要搞當然是先選一個簡單的來搞,畢竟誰都喜歡撿軟柿子捏。那哪個最簡單吶,不管你們認為是哪個反正我覺得微博的看起來簡單一點。昨天下午趁著有點時間簡單的實現(xiàn)了一下微博的刷新加載效果。先別急,咱一步一步慢慢來。首先觀察一下整體結構,界面分成三部分。

  • 頭部刷新布局
  • 可滾動控件(ListView,RecycleView)
  • 尾部加載布局

可以看成剛開始的時候頭部刷新布局和尾部都藏在可滾動布局的下面,當滾動到上下邊界的時候才一點點顯示出來,很容易想到通過繼承FrameLayout實現(xiàn)。為了提高擴展性我們在真正的頭部布局和尾部布局外面再套一層布局,看下面的具體代碼就能明白。在onAttachedToWindow方法中創(chuàng)建外層頭部尾部布局最為合適,這時候自定義的控件已經(jīng)附著到根布局上。
<pre>
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();

    //添加頭部
    if (mHeadLayout == null) {
        FrameLayout headViewLayout = new FrameLayout(getContext());
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        layoutParams.gravity = Gravity.TOP;
        headViewLayout.setLayoutParams(layoutParams);
        headViewLayout.setBackgroundColor(Color.parseColor("#F2F2F2"));
        mHeadLayout = headViewLayout;
        this.addView(mHeadLayout);
    }

    //添加底部
    if (mBottomLayout == null) {
        FrameLayout bottomViewLayout = new FrameLayout(getContext());
        LayoutParams layoutParams2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        layoutParams2.gravity = Gravity.BOTTOM;
        bottomViewLayout.setLayoutParams(layoutParams2);
        bottomViewLayout.setBackgroundColor(Color.parseColor("#F2F2F2"));
        mBottomLayout = bottomViewLayout;
        this.addView(mBottomLayout);
    }

    mChildView = getChildAt(0);
    if (mChildView == null) return;
}

</pre>

加上mHeadLayout == null和mBottomLayout == null的判斷是因為執(zhí)行onResume會重新觸發(fā)onAttachedToWindow()重復創(chuàng)建HeadLayout和BottomLayout,接下就要分析刷新和加載的狀態(tài)
刷新狀態(tài):

  • 下拉刷新
  • 釋放刷新 (箭頭旋轉)
  • 正在刷新(隱藏箭頭,顯示刷新動畫)

加載狀態(tài):

  • 加載中
  • 加載結束

對應的頭部刷新控件如下
<pre>
public class SinaRefreshView extends FrameLayout implements IHeaderView{
private ImageView refreshArrow;
private ImageView loadingView;
private TextView refreshTextView;

public SinaRefreshView(Context context) {
    this(context, null);
}

public SinaRefreshView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public SinaRefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init(){
    View rootView = View.inflate(getContext(), R.layout.layout_sinaheader, null);
    refreshArrow = (ImageView) rootView.findViewById(R.id.iv_arrow);
    refreshTextView = (TextView) rootView.findViewById(R.id.tv);
    loadingView = (ImageView) rootView.findViewById(R.id.iv_loading);
    addView(rootView);
}

private String pullDownStr = "下拉刷新";
private String releaseRefreshStr = "釋放刷新";
private String refreshingStr = "正在刷新";

@Override
public void onPullingDown(float fraction, float headHeight) {
    if (fraction < 1f) refreshTextView.setText(pullDownStr);
    if (fraction > 1f) refreshTextView.setText(releaseRefreshStr);
    refreshArrow.setRotation(fraction  * 180);
}

@Override
public void onPullReleasing(float fraction, float headHeight) {
    if (fraction < 1f) {
        refreshTextView.setText(pullDownStr);
        refreshArrow.setRotation(fraction * 180);
        if (refreshArrow.getVisibility() == GONE) {
            refreshArrow.setVisibility(VISIBLE);
            loadingView.setVisibility(GONE);
        }
    }
}

@Override
public void startAnim() {
    refreshTextView.setText(refreshingStr);
    refreshArrow.setVisibility(GONE);
    loadingView.setVisibility(VISIBLE);
    ((AnimationDrawable)loadingView.getDrawable()).start();
}

}
</pre>

對應的布局
<pre>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
>

<ImageView
    android:id="@+id/iv_arrow"
    android:layout_width="24dp"
    android:layout_height="24dp"
    android:src="@drawable/ic_arrow"/>

<ImageView
    android:id="@+id/iv_loading"
    android:layout_width="34dp"
    android:layout_height="34dp"
    android:src="@drawable/anim_loading_view"
    android:visibility="gone"/>

<TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:text="下拉刷新"
    android:textSize="16sp"/>

</LinearLayout>
</pre>

對應的尾部加載控件
<pre>
public class LoadingView extends ImageView implements IBottomView{
public LoadingView(Context context) {
this(context, null);
}

public LoadingView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    int size = SettingUtil.dip2px(context,48);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(size,size);
    params.gravity = Gravity.CENTER;
    setLayoutParams(params);
    setImageResource(R.drawable.anim_loading_view);
}

@Override
public void startAnim() {
    ((AnimationDrawable)getDrawable()).start();
}

@Override
public void onFinish() {
    ((AnimationDrawable)getDrawable()).stop();
}

}
</pre>

接下來設置頭部布局和尾部布局,布局這一塊算是徹底搞定了
<pre>
public void setHeaderView(final IHeaderView headerView) {
if (headerView != null) {
mHeadLayout.removeAllViewsInLayout();
mHeadLayout.addView(headerView.getView());
mHeadView = headerView;
}
}

public void setBottomView(final IBottomView bottomView) {
    if (bottomView != null) {
        mBottomLayout.removeAllViewsInLayout();
        mBottomLayout.addView(bottomView.getView());
        mBottomView = bottomView;
    }
}

</pre>

然后就是重點了,分析觸摸事件,這里用到兩個方法onInterceptTouchEvent和onTouchEvent,什么時候打斷觸摸事件的傳遞,自己消耗

  • 滾動到上邊界,滾動的view無法再滾動
  • 滾動到下邊界,滾動的view無法再滾動

<pre>
/**
* 攔截觸摸事件
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
mTouchY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
float dy = event.getY() - mTouchY;
if (dy > 0 && !ScrollingUtil.canChildScrollUp(mChildView)){
state = PULL_DOWN_REFRESH;
return true;
}else if (dy < 0 && !ScrollingUtil.canChildScrollDown(mChildView)){
state = PULL_UP_LOAD;
return true;
}
break;
case MotionEvent.ACTION_UP:

            break;
    }
    return super.onInterceptTouchEvent(event);
}

</pre>

這里可以通過ViewCompat.canScrollVertically(mChildView, 1);來判斷滾動的view是否可以再滾動。接下來就是消耗觸摸事件。
處于下拉刷新狀態(tài)的情況下:

  • 隨著手指的下拉,同步刷新頭部布局的高度,以及通過setTranslationY()使得滾動控件在Y方向上偏移,同時設置頭部控件的狀態(tài)。
  • 手指釋放時判斷頭部布局的高度是否達到了刷新要求,若沒有達到刷新要求直接回滾。若達到了刷新要求先回到刷新高度,然后執(zhí)行刷新動畫以及刷新回調。

處于上拉加載的情況的:

  • 隨著手指的下拉,當下拉距離小于設置的尾部高度時,同步刷新尾部布局的高度,以及通過setTranslationY()使得滾動控件在Y方向上偏移,同時設置尾部控件的狀態(tài)。
  • 手指釋放時判斷尾部布局的高度是否達到了加載要求,若沒有達到加載要求直接回滾。若達到了加載要求,然后執(zhí)行加載動畫以及加載回調。
    <pre>
    /**
    • 觸摸事件
      */
      @Override
      public boolean onTouchEvent(MotionEvent event) {
      if (isRefreshing || isLoadingmore) return super.onTouchEvent(event);

      switch (event.getAction()){
      case MotionEvent.ACTION_MOVE:
      float dy = event.getY() - mTouchY;
      float offsetY = dy/2;
      if (state == PULL_DOWN_REFRESH) {
      dy = Math.max(0, offsetY);
      mChildView.setTranslationY(dy);
      mHeadLayout.getLayoutParams().height = (int) dy;
      mHeadLayout.requestLayout();
      if(dy/refreshHeadHeight<1.02)
      mHeadView.onPullingDown(dy/refreshHeadHeight,refreshHeadHeight);
      }else if (state == PULL_UP_LOAD) {
      if(offsetY>0){
      break;
      }
      dy = Math.min(bottomHeight, Math.abs(offsetY));
      dy = Math.max(0, dy);
      mChildView.setTranslationY(-dy);
      mBottomLayout.getLayoutParams().height = (int)dy;
      mBottomLayout.requestLayout();
      }
      break;
      case MotionEvent.ACTION_UP:
      if (state == PULL_DOWN_REFRESH) {
      if(mChildView.getTranslationY() >= refreshHeadHeight){
      animChildView(refreshHeadHeight);
      isRefreshing = true;
      mHeadView.startAnim();
      if(mOnRefreshListener!=null)
      mOnRefreshListener.onRefresh(LXSRefreshLayout.this);
      }else{
      animChildView(0);
      }
      } else if (state == PULL_UP_LOAD) {
      if(Math.abs(mChildView.getTranslationY()) >= bottomHeight){
      isLoadingmore = true;
      mBottomView.startAnim();
      animChildView(-bottomHeight);
      if(mOnRefreshListener!=null)
      mOnRefreshListener.onLoadMore(LXSRefreshLayout.this);
      }else{
      animChildView(0);
      }
      }
      break;
      }
      return super.onTouchEvent(event);
      }
      </pre>

這里有兩個注意點:

  • 當處于刷新和加載狀態(tài)下時消耗掉觸摸事件
  • move過程需要判斷一下是否滑動到了邊緣,不然會有問題

當沒有達到刷新或則加載要求的時候需要回滾,直接通過mChildView.setTranslationY(0)太過于生硬,這邊通過屬性動畫過度
<pre>
private void animChildView(float endValue, long duration) {
ObjectAnimator oa = ObjectAnimator.ofFloat(mChildView, "translationY", mChildView.getTranslationY(), endValue);
oa.setDuration(duration);
oa.setInterpolator(new DecelerateInterpolator());//設置速率為遞減
oa.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int height = (int) mChildView.getTranslationY();
if (state == PULL_DOWN_REFRESH) {
mHeadLayout.getLayoutParams().height = height;
mHeadLayout.requestLayout();
mHeadView.onPullReleasing(height/refreshHeadHeight,refreshHeadHeight,refreshHeadHeight);
}else if (state == PULL_UP_LOAD) {
mBottomLayout.getLayoutParams().height = -height;
mBottomLayout.requestLayout();
}
}
});
oa.start();
}
</pre>

最后是設置回調接口以及刷險加載結束的處理方法
<pre>
/**
* 刷新結束
*/
public void finishRefreshing() {
isRefreshing = false;
if (mChildView != null) {
animChildView(0f);
}
}

/**
 * 加載更多結束
 */
public void finishLoadmore() {
    isLoadingmore = false;
    if (mChildView != null) {
        animChildView(0f);
        mBottomView.onFinish();
    }
}

public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
    mOnRefreshListener = onRefreshListener;
}

public interface OnRefreshListener{
    void onRefresh(LXSRefreshLayout refreshLayout);
    void onLoadMore(LXSRefreshLayout refreshLayout);
}

</pre>

使用方法跟SwipeRefreshLayout一模一樣,運行起來的效果大概是這樣的:

刷新加載-1.gif
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容