Android中自定義SmartRefreshLayout的下拉刷新動(dòng)畫(header)和上拉加載動(dòng)畫(footer)(五)

SmartRefreshLayout是一個(gè)很優(yōu)秀的下拉刷新控件。前面我已經(jīng)寫過他配合RecyclerView的下拉刷新。但是所使用的頭文件動(dòng)畫是他內(nèi)部自帶的,而我們平時(shí)的使用中大多數(shù)都是使用公司吉祥物或者logo來展示。所以在此做一篇單獨(dú)的介紹。

說明:

一,使用的Androidstudio版本為3.3

二,SmartRefreshLayout是智能的下拉刷新框架。如何使用請(qǐng)看如下文章。

Android中RecyclerView配合SmartRefreshLayout實(shí)現(xiàn)下拉刷新以及優(yōu)化(二):http://www.itdecent.cn/p/0d37b5e21c09

展示如下

https://upload-images.jianshu.io/upload_images/14906070-b7dc97ef211a0b57.gif?imageMogr2/auto-orient/strip

現(xiàn)在正式開始(下拉刷新部分)

1,在build.gradle中增加下拉刷新SmartRefreshLayout的依賴和butterknife依賴

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.mumu.jsrecyclerview5"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
//1,增加jitpack支持
allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
        flatDir {
            dirs 'libs'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    //2,butterKnife
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

    //3,增加下拉刷新SmartRefreshLayout的依賴
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-alpha-21'
    implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.1.0-alpha-21'

}

2,在drawable中添加圖片的資源文件,這需要注意,放資源文件的時(shí)候不要放進(jìn)v24里面去了,不然有些手機(jī)會(huì)報(bào)錯(cuò)找不到資源id,會(huì)閃退。

image.png

drawable/anim_pull_refreshing.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<animation-list android:oneshot="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_01" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_02" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_03" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_02" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_05" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_06" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_07" />
    <item android:duration="50" android:drawable="@drawable/commonui_refreshing_image_frame_06" />
</animation-list>

/drawable/anim_pull_end.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">

    <item
        android:drawable="@drawable/commonui_pull_end_image_frame_01"
        android:duration="100" />

    <item
        android:drawable="@drawable/commonui_pull_end_image_frame_02"
        android:duration="100" />

    <item
        android:drawable="@drawable/commonui_pull_end_image_frame_03"
        android:duration="100" />

    <item
        android:drawable="@drawable/commonui_pull_end_image_frame_04"
        android:duration="100" />

    <item
        android:drawable="@drawable/commonui_pull_end_image_frame_05"
        android:duration="100" />

</animation-list>

3,增加自定義的activity文件,如下,最重要的6個(gè)步驟都有注釋,核心在第五步,要搞清楚這個(gè)動(dòng)畫的三個(gè)關(guān)鍵時(shí)間段。第一個(gè)時(shí)間段:下拉過程,第二個(gè)時(shí)間段:下拉到底部最大值,第三個(gè)時(shí)間段:松開手指。而第五步中的三個(gè)狀態(tài)分別是這三個(gè)時(shí)間段的初始化狀態(tài)。

package com.mumu.jsrecyclerview5;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshKernel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;

public class MRefreshHeader extends LinearLayout implements RefreshHeader {

    private ImageView mImage;
    private AnimationDrawable mAnimPull;
    private AnimationDrawable mAnimRefresh;

    /**
     * 1,構(gòu)造方法
     */
    public MRefreshHeader(Context context) {
        this(context, null, 0);
    }

    public MRefreshHeader(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MRefreshHeader(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = View.inflate(context, R.layout.m_refresh_header, this);
        mImage = view.findViewById(R.id.iv_refresh_header);
    }

    /**
     * 2,獲取真實(shí)視圖(必須返回,不能為null)一般就是返回當(dāng)前自定義的view
     */
    @NonNull
    @Override
    public View getView() {
        return this;
    }

    /**
     * 3,獲取變換方式(必須指定一個(gè):平移、拉伸、固定、全屏),Translate指平移,大多數(shù)都是平移
     */
    @NonNull
    @Override
    public SpinnerStyle getSpinnerStyle() {
        return SpinnerStyle.Translate;
    }

    /**
     * 4,執(zhí)行下拉的過程
     *
     * @param isDragging
     * @param percent
     * @param offset
     * @param height
     * @param maxDragHeight
     */
    @Override
    public void onMoving(boolean isDragging, float percent, int offset, int height, int maxDragHeight) {
        if (percent < 1) {
            mImage.setScaleX(percent);
            mImage.setScaleY(percent);
        }
    }

    /**
     * 5,一般可以理解為一下case中的三種狀態(tài),在達(dá)到相應(yīng)狀態(tài)時(shí)候開始改變
     * 注意:這三種狀態(tài)都是初始化的狀態(tài)
     */
    @Override
    public void onStateChanged(@NonNull RefreshLayout refreshLayout, @NonNull RefreshState oldState, @NonNull RefreshState newState) {
        switch (newState) {
            //1,下拉刷新的開始狀態(tài):下拉可以刷新
            case PullDownToRefresh:
                mImage.setImageResource(R.drawable.commonui_pull_image);
                break;
            //2,下拉到最底部的狀態(tài):釋放立即刷新
            case ReleaseToRefresh:
                mImage.setImageResource(R.drawable.anim_pull_end);
                mAnimPull = (AnimationDrawable) mImage.getDrawable();
                mAnimPull.start();
                break;
            //3,下拉到最底部后松手的狀態(tài):正在刷新
            case Refreshing:
                mImage.setImageResource(R.drawable.anim_pull_refreshing);
                mAnimRefresh = (AnimationDrawable) mImage.getDrawable();
                mAnimRefresh.start();
                break;
        }
    }

    /**
     * 6,結(jié)束下拉刷新的時(shí)候需要關(guān)閉動(dòng)畫
     *
     * @param refreshLayout
     * @param success
     * @return
     */
    @Override
    public int onFinish(@NonNull RefreshLayout refreshLayout, boolean success) {
        if (mAnimRefresh != null && mAnimRefresh.isRunning()) {
            mAnimRefresh.stop();
        }
        if (mAnimPull != null && mAnimPull.isRunning()) {
            mAnimPull.stop();
        }
        return 0;
    }

    @Override
    public void onReleased(@NonNull RefreshLayout refreshLayout, int height, int maxDragHeight) {

    }

    @Override
    public void onStartAnimator(@NonNull RefreshLayout refreshLayout, int height, int maxDragHeight) {

    }

    @Override
    public void setPrimaryColors(int... colors) {

    }

    @Override
    public void onInitialized(@NonNull RefreshKernel kernel, int height, int maxDragHeight) {

    }

    @Override
    public void onHorizontalDrag(float percentX, int offsetX, int offsetMax) {

    }

    @Override
    public boolean isSupportHorizontalDrag() {
        return false;
    }
}

4,對(duì)應(yīng)的xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="@color/white"
    android:padding="5dp"
    android:gravity="center"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/iv_refresh_header"
        android:scaleX="0"
        android:scaleY="0"
        android:translationY="0dp"
        android:layout_width="41dp"
        android:layout_height="54dp" />
</LinearLayout>

現(xiàn)在正式開始(上拉加載部分)

5,自定義的footer文件,注意點(diǎn):1,原來的footer是稍微上拉就會(huì)觸發(fā)刷新,用戶基本無感知,簡(jiǎn)書app就是如此做法,現(xiàn)在更改后是上滑松手后開始刷新操作。具體需求看公司要求。只需要重寫onInitialized方法,增加或者刪除該方法里面的代碼即可。2,在onStateChanged方法中,PullUpToLoad下開始動(dòng)畫就是剛剛上拉就執(zhí)行。

package com.mumu.jsrecyclerview5;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshKernel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;

/**
 * @author : zlf
 * date    : 2019-04-19
 * github  : https://github.com/mamumu
 * blog    : http://www.itdecent.cn/u/281e9668a5a6
 */
public class MRefreshFooter extends LinearLayout implements RefreshFooter {

    private ImageView mImage;
    private Animation mAnim;

    public MRefreshFooter(Context context) {
        this(context, null, 0);
    }

    public MRefreshFooter(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MRefreshFooter(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = View.inflate(context, R.layout.m_refresh_footer, this);
        mImage = view.findViewById(R.id.iv_refresh_footer);
        mAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_round_rotate);
        LinearInterpolator linearInterpolator = new LinearInterpolator();
        mAnim.setInterpolator(linearInterpolator);

    }


    @Override
    public boolean setNoMoreData(boolean noMoreData) {
        return false;
    }

    @NonNull
    @Override
    public View getView() {
        return this;
    }

    @NonNull
    @Override
    public SpinnerStyle getSpinnerStyle() {
        return SpinnerStyle.Translate;
    }

    @Override
    public void setPrimaryColors(int... colors) {

    }

    @Override
    public void onInitialized(@NonNull RefreshKernel kernel, int height, int maxDragHeight) {
        //控制是否稍微上滑動(dòng)就刷新
        kernel.getRefreshLayout().setEnableAutoLoadMore(false);
    }

    @Override
    public void onMoving(boolean isDragging, float percent, int offset, int height, int maxDragHeight) {

    }

    @Override
    public void onReleased(@NonNull RefreshLayout refreshLayout, int height, int maxDragHeight) {

    }

    @Override
    public void onStartAnimator(@NonNull RefreshLayout refreshLayout, int height, int maxDragHeight) {
    }

    @Override
    public int onFinish(@NonNull RefreshLayout refreshLayout, boolean success) {
        if(mAnim != null && mAnim.hasStarted() && !mAnim.hasEnded()){
            mAnim.cancel();
            mImage.clearAnimation();
        }
        return 0;
    }

    @Override
    public void onHorizontalDrag(float percentX, int offsetX, int offsetMax) {

    }

    @Override
    public boolean isSupportHorizontalDrag() {
        return false;
    }

    @Override
    public void onStateChanged(@NonNull RefreshLayout refreshLayout, @NonNull RefreshState oldState, @NonNull RefreshState newState) {
        switch (newState) {
            case None:
            case PullUpToLoad:
                if (mAnim != null) {
                    mImage.startAnimation(mAnim);
                }
                break;
            case Loading:

            case LoadReleased:

                break;
            case ReleaseToLoad:
                break;
        }
    }
}

6,自定義的footer文件對(duì)應(yīng)的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="5dp">

    <ImageView
        android:id="@+id/iv_refresh_footer"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:src="@drawable/default_ptr_rotate" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="讓你放心 才是對(duì)的"
        android:textSize="11sp" />
</LinearLayout>

7,MainActivity,如果進(jìn)行實(shí)際的網(wǎng)絡(luò)請(qǐng)求,那么可以在網(wǎng)絡(luò)請(qǐng)求結(jié)束后關(guān)閉,調(diào)用如下3即可。

package com.mumu.jsrecyclerview5;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.smart)
    SmartRefreshLayout smart;
    @BindView(R.id.text)
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        smartRefreshView();
    }

    /**
     * 1,刷新控件的監(jiān)聽
     */
    private void smartRefreshView() {
        smart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                //延遲3秒關(guān)閉
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishLoadMore();
                    }
                }, 3000);

            }

            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                //2,刷新完成關(guān)閉,正常情況是請(qǐng)求接口完成關(guān)閉
                //3,如果需要在網(wǎng)絡(luò)請(qǐng)求結(jié)束后關(guān)閉,則調(diào)用
//                smart.finishRefresh();
//                smart.finishLoadMore();
                refreshLayout.finishRefresh();
                refreshLayout.setNoMoreData(true);
            }
        });
    }


    @OnClick(R.id.text)
    public void onViewClicked() {
        smart.finishRefresh();
    }
}

6,MainActivity對(duì)應(yīng)的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/smart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srlAccentColor="#00000000"
        app:srlEnablePreviewInEditMode="true"
        app:srlPrimaryColor="#00000000">

        <com.mumu.jsrecyclerview5.MRefreshHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#5500ff00"
            android:gravity="center">

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="我愛安卓"
                android:textColor="#ff00ff"
                android:textSize="30sp" />
        </LinearLayout>

        <com.mumu.jsrecyclerview5.MRefreshFooter
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>
</LinearLayout>

7,使用起來很簡(jiǎn)單,直接將自定義的這個(gè)view放在SmartRefreshLayout中就可以了,如第六步xml所示。

8,對(duì)應(yīng)github地址

demo地址:https://github.com/mamumu/jsRecyclerView5

9,特別感謝:https://github.com/cachecats/LikeMeiTuan

如果有發(fā)現(xiàn)錯(cuò)誤歡迎指正我及時(shí)修改,如果有好的建議歡迎留言。如果覺得對(duì)你有幫助歡迎給小星星,謝謝。

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容