Android flexible switch pull-down refresh (policy mode + reflection)

Keywords: Retrofit Android Java github

Recently, I want to change the pull-down to refresh, but I don't want to discard the previous one. I want to know whether both of them can coexist. Before using it, configure A to use A, and configure B to use B. (the principle is to control the use of corresponding strategies through reflection)
It is very simple to use. You can directly switch the drop-down refresh mode by modifying the mode type:

//Mode 1
private int refreshMode = RefreshContext.SWIPE_REFRESH;
//Mode two
private int refreshMode = RefreshContext.PTR_REFRESH;


Let's start the transformation

1. Define interface

public interface IRefresh {
    void onRefresh(AppCompatActivity activity, OnRefreshListener onRefreshListener);
 //auto refresh
    void autoRefresh();
  //Refresh finish
    void onRefreshComplete();
}

2. Definition notes

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mode {
    int value() default RefreshContext.SWIPE_REFESH;
}

3. Define callbacks for external calls

public interface OnRefreshListener {
    void onRefresh();
}

4. Specific implementation classes (several refresh modes are defined, here are two)

@Mode(RefreshContext.SWIPE_REFRESH)
public class SwipeRefresh implements IRefresh {

    private SwipeRefreshLayoutFinal swipeRefreshLayoutFinal;

    @Override
    public void onRefresh(AppCompatActivity activity, final OnRefreshListener onRefreshListener) {
        //activity.setContentView(R.layout.layout_swipe);
        swipeRefreshLayoutFinal = (SwipeRefreshLayoutFinal) activity.findViewById(R.id.swl_layout);
        swipeRefreshLayoutFinal.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (null != onRefreshListener) {
                    onRefreshListener.onRefresh();
                }
            }
        });
    }

    @Override
    public void autoRefresh() {
        swipeRefreshLayoutFinal.autoRefresh();
    }

    @Override
    public void onRefreshComplete() {
        swipeRefreshLayoutFinal.onRefreshComplete();
    }
}
@Mode(RefreshContext.PTR_REFRESH)
public class PtrRefresh implements IRefresh {

    private PtrClassicFrameLayout ptrClassicFrameLayout;

    @Override
    public void onRefresh(AppCompatActivity activity, final OnRefreshListener onRefreshListener) {
        ptrClassicFrameLayout = (PtrClassicFrameLayout) activity.findViewById(R.id.ptr_rv_layout);
        setHeaderView(activity, ptrClassicFrameLayout);
        ptrClassicFrameLayout.setLastUpdateTimeRelateObject(this);
        ptrClassicFrameLayout.disableWhenHorizontalMove(true);
        ptrClassicFrameLayout.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (null != onRefreshListener) {
                    onRefreshListener.onRefresh();
                }
            }
        });
    }

    @Override
    public void autoRefresh() {
        ptrClassicFrameLayout.autoRefresh();
    }

    @Override
    public void onRefreshComplete() {
        ptrClassicFrameLayout.onRefreshComplete();
    }

    private void setHeaderView(AppCompatActivity activity, PtrClassicFrameLayout ptrRvLayout) {
        StoreHouseHeader header = new StoreHouseHeader(activity);
        header.setPadding(0, (int) ScreenUtils.dpToPxInt(activity, 20), 0, (int) ScreenUtils.dpToPxInt(activity, 10));
        header.setTextColor(activity.getResources().getColor(R.color.colorPrimary));
        header.initWithString("LOADING", 20);
        ptrRvLayout.setLoadingMinTime(1000);
        ptrRvLayout.setDurationToClose(50);
        ptrRvLayout.setDurationToCloseHeader(1000);
        ptrRvLayout.setHeaderView(header);
        ptrRvLayout.addPtrUIHandler(header);
    }
}

5. Context

public class RefreshContext {

    public static final int SWIPE_REFRESH = 1;
    public static final int PTR_REFRESH = 2;

    private int refreshMode;
    private OnRefreshListener onRefreshListener;

    private List<Class<? extends IRefresh>> refreshList;
    private IRefresh iRefresh;
    private final WeakReference<AppCompatActivity> weakReference;

    public RefreshContext(AppCompatActivity activity, int refreshMode) {

        weakReference = new WeakReference<>(activity);
        this.refreshMode = refreshMode;
    }


    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        this.onRefreshListener = onRefreshListener;
        init();
    }

    //auto refresh
    public void autoRefresh() {
        iRefresh.autoRefresh();

    }
    //Refresh finish
    public void onRefreshComplete() {
        iRefresh.onRefreshComplete();
    }

//------------------------------Reflection get annotation-----------------------------------

    private void init() {
        refreshList = new ArrayList<>();

        try {
            String packageName = getClass().getPackage().getName();
            Class<?> getRequestParams = Class.forName(packageName + ".PtrRefresh");
            Class<?> postRequestParams = Class.forName(packageName + ".SwipeRefresh");
            List<Class<?>> classList = new ArrayList<>();
            classList.add(getRequestParams);
            classList.add(postRequestParams);

            for (int i = 0; i < classList.size(); i++) {
                Class<?> clazz = classList.get(i);
                //judgeclazzWhether it isIRequestParamImplementation class
                if (IRefresh.class.isAssignableFrom(clazz)) {
                    refreshList.add((Class<? extends IRefresh>) clazz);
                }
            }


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        iRefresh = chooseRequest(refreshMode);
        AppCompatActivity activity = weakReference.get();
        if (null != activity) {
            iRefresh.onRefresh(activity, onRefreshListener);
        }
    }


    //Generate the corresponding method according to the returned method
    public IRefresh chooseRequest(int refreshMode) {

        //Find policy in policy list
        for (Class<? extends IRefresh> clazz : refreshList) {
            //Get comments for this policy
            Mode method = clazz.getAnnotation(Mode.class);
            if (refreshMode == method.value()) {
                try {
                    return clazz.newInstance();
                } catch (Exception e) {
                    throw new RuntimeException("Policy acquisition failed");
                }
            }
        }

        throw new RuntimeException("Policy acquisition failed");
    }

}

Finally, the client calls

package com.zx.rxjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zx.rxjava.bean.Vip;
import com.zx.rxjava.refresh.OnRefreshListener;
import com.zx.rxjava.refresh.RefreshContext;
import com.zx.rxjava.service.RetrofitService;
import com.zx.rxjava.tools.ListUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.loadingviewfinal.OnLoadMoreListener;
import cn.finalteam.loadingviewfinal.RecyclerViewFinal;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class VipListActivity extends AppCompatActivity {

    private RefreshContext refreshContext;
    private int mPage = 1;
    private RecyclerViewFinal mRvList;
    private List<Vip> mVipList = new ArrayList<>();
    private CommonAdapter mCommonAdapter;

    public static final int PAGE_SIZE = 20;

    HashMap<Integer, Integer> modeList = new HashMap<>();
    private int refreshMode = RefreshContext.PTR_REFRESH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initRefresh();
        setContentView(modeList.get(refreshMode));
        initView();
    }

    private void initRefresh() {
        refreshContext = new RefreshContext(this, refreshMode);
        modeList.put(RefreshContext.PTR_REFRESH, R.layout.layout_ptr);
        modeList.put(RefreshContext.SWIPE_REFRESH, R.layout.layout_swipe);
    }

    private void initView() {
        mRvList = (RecyclerViewFinal) findViewById(R.id.rv_list);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
        mCommonAdapter = new CommonAdapter<Vip>(this, R.layout.listitem_vip, mVipList) {
            @Override
            protected void convert(ViewHolder holder, Vip vip, int position) {
                holder.setText(R.id.tv_name, vip.getCustomerName());
            }

        };
        mRvList.setAdapter(mCommonAdapter);
        refreshContext.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                request(1);
            }
        });
        refreshContext.autoRefresh();

        mRvList.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                request(mPage);
            }
        });
    }


    private void request(final int page) {
        Retrofit retrofit = AppClient.retrofit(getApplicationContext());
        RetrofitService retrofitService = retrofit.create(RetrofitService.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageSize", PAGE_SIZE);
        map.put("pageNum", page);

        Call<GetVipListRespons> call = retrofitService.getVipListBody(map);
        call.enqueue(new Callback<GetVipListRespons>() {
            @Override
            public void onResponse(Call<GetVipListRespons> call, Response<GetVipListRespons> response) {
                List<Vip> vipList = response.body().getData().getRows();

                if (ListUtils.isEmpty(vipList)) {
                    vipList = new ArrayList<>();
                }
                if (page == 1) {
                    mVipList.clear();
                }
                mPage = page + 1;
                mVipList.addAll(vipList);
                mRvList.setHasLoadMore(vipList.size() < PAGE_SIZE ? false : true);
                mCommonAdapter.notifyDataSetChanged();
                refreshContext.onRefreshComplete();
                mRvList.onLoadMoreComplete();

            }

            @Override
            public void onFailure(Call<GetVipListRespons> call, Throwable t) {

            }
        });
    }
}

The code is very simple, and there is not much explanation. Just use refreshContext as a drop-down refresh View.

Attachment: open source projects used

https://github.com/hongyangAndroid/baseAdapter
https://github.com/pengjianbo/LoadingViewFinal

Posted by ShaileshD on Sun, 05 Apr 2020 06:05:10 -0700