Android中recyclerview+pullToRefresh實現上拉重新整理和下拉載入
阿新 • • 發佈:2018-12-30
一. 依賴
implementation 'com.jwenfeng.pulltorefresh:library:1.0.3'
要把minSdkVersion 改為16以上
二.佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragment.UserFragment"> <com.jwenfeng.library.pulltorefresh.PullToRefreshLayout android:id="@+id/pullToregresh" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/userRecyclerview" android:layout_width="match_parent" android:layout_height="match_parent" /> </com.jwenfeng.library.pulltorefresh.PullToRefreshLayout> </LinearLayout>
在activity中
public class UserFragment extends Fragment implements IUserView { private PullToRefreshLayout pullToregresh; private RecyclerView userRecyclerview; private UserPresenter userPresenter; private int count=0; private ArrayList<UserBaen.DataBean> list = new ArrayList<>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user, container, false); pullToregresh = view.findViewById(R.id.pullToregresh); userRecyclerview = view.findViewById(R.id.userRecyclerview); userPresenter = new UserPresenter(this); userPresenter.showUser(1); pullToregresh.setRefreshListener(new BaseRefreshListener() { @Override public void refresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { //清除 list.clear(); userPresenter.showUser(1); pullToregresh.finishRefresh(); } },2000); } @Override public void loadMore() { new Handler().postDelayed(new Runnable() { @Override public void run() { count++; userPresenter.showUser(count); pullToregresh.finishLoadMore(); } },2000); } }); return view; } @Override public void Success(final List<UserBaen.DataBean> result) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { //把所有的資料放在list中 list.addAll(result); UserAdapter userAdapter = new UserAdapter(getContext(), list); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); userRecyclerview.setLayoutManager(linearLayoutManager); userRecyclerview.setAdapter(userAdapter); } }); } @Override public void Failer(String msg) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), "失敗", Toast.LENGTH_SHORT).show(); } }); } }