为了账号安全,请及时绑定邮箱和手机立即绑定

Android开发笔记——RecyclerView下拉刷新、上拉更多以及点击显示扩展菜单 ...

标签:
Android

1.以下代码是在Fragment加载,修改为Activity加载很简单:

public class MyFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, 
                                                        RequestHistoryUtils.OnRequestCallback {

    public static final  int                MODE_LOAD              = 0;
    public static final  int                MODE_LOAD_MORE         = 1;
    public static final  int                MODE_LOAD_PULL_REFRESH = 2;
    private static final int                VIEW_TYPE_ITEM         = 0;
    private static final int                VIEW_TYPE_PANEL        = 1;
    private static final int                VIEW_TYPE_FOOTER       = 2;
    private              MyApplication   _app                   = null;
    private              int                _panelPosition         = -1;
    private              SwipeRefreshLayout _srRefresh             = null;
    private              RecyclerView       _listView              = null;
    private              List<BeanData>    _data                  = null;
    private              MyAdapter          _adapter               = null;
    private              int                _currentMode           = 0;

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager())						       .findLastCompletelyVisibleItemPosition();
            if (lastVisibleItem == _data.size() && _data.size() > 0 && dy > 0 &&                                                                   _adapter.isCanLoadMore()) {
                requestHttp(MODE_LOAD_MORE);
            } else {
                _srRefresh.setRefreshing(false);
            }
        }
    };

    /**
     * Pull down to load the latest first page data
     * For search result
     * For common history
     */
    @Override
    public void onRefresh() {
        requestHttp(MODE_LOAD_PULL_REFRESH);
    }

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _app = ((MyApplication) getActivity().getApplicationContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                                                                   Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout., container, false);

        _srRefresh = rootView.findViewById(R.id.sr_refresh);
        _srRefresh.setColorSchemeResources(R.color.color_btn_login_normal);
        _srRefresh.setProgressBackgroundColorSchemeResource(R.color.color_item_line);

        _data = new ArrayList<>();
        _listView = rootView.findViewById(R.id.listView);
        _listView.setLayoutManager(new LinearLayoutManager(getActivity()));
        _adapter = new MyAdapter(getActivity());
        _listView.setAdapter(_adapter);
        _listView.setHasFixedSize(true);
        _listView.setItemAnimator(new DefaultItemAnimator());
        _srRefresh.setOnRefreshListener(this);

        _listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestHttp(MODE_LOAD);
            }
        }, DELAY_LOAD_TIME);
        _listView.addOnScrollListener(onScrollListener);
        return rootView;
    }

    protected void insertItemByPosition(int position) {
        RemoveItemByIsPanel();
        if (_panelPosition != -1 && _panelPosition < position) {
            position = position - 1;
        }
        if (_panelPosition != position) {
            _panelPosition = position;
            if (_adapter != null && position > 0) {
                _adapter.notifyItemInserted(position);
                BeanData data = new BeanData();
                data.setIsPanel(true);
                _data.add(position, event);
                _adapter.notifyItemRangeChanged(position, _adapter.getItemCount());
            }
            _listView.smoothScrollToPosition(position);
        } else {
            _panelPosition = -1;
        }
        _adapter.notifyItemRangeChanged(0, _adapter.getItemCount());
    }

    protected void RemoveItemByIsPanel() {
        for (int i = 0; i < _data.size(); i++) {
            if (_data.get(i).isPanel()) {
                _adapter.notifyItemRemoved(i);
                _data.remove(i);
                _adapter.notifyItemRangeChanged(i, _adapter.getItemCount());
            }
        }
    }

    private class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private LayoutInflater listContainer;
        private boolean isCanLoadMore  = false;

        MyAdapter(Context context) {
            listContainer = LayoutInflater.from(context);
        }

        private boolean isCanLoadMore() {
            return isCanLoadMore;
        }

        private void setIsCanLoadMore(Boolean isCanLoadMore) {
            this.isCanLoadMore = isCanLoadMore;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            if (viewType == VIEW_TYPE_ITEM) {
                View view = listContainer.inflate(R.layout.layout_list_item_content, viewGroup, false);
                return new ItemViewHolder(view);
            } else if (viewType == VIEW_TYPE_PANEL) {
                View view = listContainer.inflate(R.layout.layout_list_item_panel, viewGroup, false);
                return new PanelViewHolder(view);
            } else if (viewType == VIEW_TYPE_FOOTER) {
                View view = listContainer.inflate(R.layout.layout_list_item_load_more_footer, viewGroup, false);
                return new FooterViewHolder(view);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, int position) {
            if (viewHolder instanceof PanelViewHolder) {
                //TODO setup data or event for UI
            } else if (viewHolder instanceof ItemViewHolder) {
                ((ItemViewHolder) viewHolder).rl_content.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        insertItemByPosition(viewHolder.getAdapterPosition() + 1);
                    }
                });

                //TODO setup data or event for UI
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override

        public int getItemCount() {
            if (_data.size() > 0 && isCanLoadMore()) {
                return _data.size() + 1;
            } else {
                return _data.size();
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (position == _data.size()) {
                return VIEW_TYPE_FOOTER;
            } else if (_data.get(position).isPanel()) {
                return VIEW_TYPE_PANEL;
            } else {
                return VIEW_TYPE_ITEM;
            }
        }

        class ItemViewHolder extends RecyclerView.ViewHolder {

            View      rl_content;

            ItemViewHolder(View itemView) {
                super(itemView);
                rl_content = itemView.findViewById(R.id.rl_content);
            }
        }

        class PanelViewHolder extends RecyclerView.ViewHolder {

            PanelViewHolder(View itemView) {
                super(itemView);
            }
        }

        class FooterViewHolder extends RecyclerView.ViewHolder {

            FooterViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    private void requestHttp(int mode) {
        _currentMode = mode;
        _requestCode++;
        RequestHistoryUtils requestHistoryUtils = new RequestHistoryUtils(_requestCode, this);
        requestHistoryUtils.loadData(mode, _data.get(data.size()-1).getIndex()+"");
    }

    @Override
    public void onRequestWillStart(int mode, int requestCode) {
        if (mode == MODE_LOAD) {
            _app.showProgressDialog(getActivity());
        }
    }

    @Override
    public void onRequestSuccess(int mode, int requestCode, List<BeanAlarm> e) {
        if (_requestCode != requestCode) {// This request was canceled by user's pressing back
            if (_currentMode == MODE_LOAD_PULL_REFRESH) {//canceled request may be open a progress bar, so need close
                _app.dismissProgressDialog();
            } else {//canceled request may be by pull down, so need close
                _srRefresh.setRefreshing(false);
            }
            return;
        }
        if (mode == MODE_LOAD) {
            _app.dismissProgressDialog();
        }
        if (getActivity() == null) {
            return;
        }
        if (e == null) {
            _app.ToastMessage(getActivity(), R.string.http_error_return_null);
            return;
        }
        if (mode == MODE_LOAD || mode == MODE_LOAD_PULL_REFRESH) {
            if (mode == MODE_LOAD_PULL_REFRESH) {
                _srRefresh.setRefreshing(false);
            }
            _data.clear();
            _data.addAll(e);
            _panelPosition = -1;
            if (_data.size() > 0 && _data.size() % RequestHistoryUtils.PAGE_SIZE == 0) {
                _adapter.setIsCanLoadMore(true);
            } else {
                _adapter.setIsCanLoadMore(false);
            }
            _adapter.notifyDataSetChanged();
            _listView.scrollToPosition(0);
        } else if (mode == MODE_LOAD_MORE) {
            _data.addAll(e);
            _panelPosition = -1;
            if (_data.size() > 0 && _data.size() % RequestHistoryUtils.PAGE_SIZE == 0) {
                _adapter.setIsCanLoadMore(true);
            } else {
                _adapter.setIsCanLoadMore(false);
            }
            _adapter.notifyDataSetChanged();
        }
        if (e.isEmpty()) {
            _app.ToastMessage(getActivity(), R.string.load_data_empty);
        }
    }

    @Override
    public void onRequestFailed(int mode, int requestCode, int errMsg) {
        if (_requestCode != requestCode) {// This request was canceled by user's pressing back
            if (_currentMode == MODE_LOAD_PULL_REFRESH) {//canceled request may be open a progress bar, so need close
                _app.dismissProgressDialog();
            } else {//canceled request may be by pull down, so need close
                _srRefresh.setRefreshing(false);
            }
            return;
        }
        if (mode == MODE_LOAD) {
            _app.dismissProgressDialog();
        }
        if (getActivity() == null) {
            return;
        }
        if (mode == MODE_LOAD_PULL_REFRESH) {
            _srRefresh.setRefreshing(false);
        }
        if (errMsg == R.string.http_error_from_service) {
            _app.ToastMessage(getActivity(), FaceDetectionApp.error_message);
        } else {
            _app.ToastMessage(getActivity(), errMsg);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            _listView.addOnScrollListener(onScrollListener);
            _listView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestHttp(MODE_LOAD);
                }
            }, DELAY_LOAD_TIME);
        } else {
            _listView.removeOnScrollListener(onScrollListener);
        }
    }
}

2.其他代码:

public class RequestHistoryUtils {
    public static final int               PAGE_SIZE         = 20;
    private             int               requestCode       = 0;
    private             OnRequestCallback onRequestCallback = null;

    public RequestHistoryUtils(int requestCode, OnRequestCallback onRequestCallback) {
        this.requestCode = requestCode;// Used to check cancel status
        this.onRequestCallback = onRequestCallback;
    }

    public interface OnRequestCallback {
        void onRequestWillStart(int mode, int requestCode);

        void onRequestSuccess(int mode, int requestCode, List<BeanAlarm> alarmList);

        void onRequestFailed(int mode, int requestCode, int errMsg);
    }

    public void setRequestCode(int requestCode) {
        this.requestCode = requestCode;
    }

    public void loadData(final int mode, String alarmIndex) {
        TaskHistory task = new TaskHistory(new AsyncTaskDelegate<List<BeanData>>() {

            @Override
            public void willStart(AsyncTask<?, ?, ?> asyncTask) {
                onRequestCallback.onRequestWillStart(mode, requestCode);
            }

            @Override
            public void onSuccess(AsyncTask<?, ?, ?> asyncTask, List<BeanData> e) {
                onRequestCallback.onRequestSuccess(mode, requestCode, e);
                onRequestCallback = null;
            }

            @Override
            public void onFailed(AsyncTask<?, ?, ?> asyncTask, Throwable t, int errMsg) {
                onRequestCallback.onRequestFailed(mode, requestCode, errMsg);
                onRequestCallback = null;
            }

            @Override
            public void onTokenOutOfDate() {
            }
        });
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, alarmIndex, PAGE_SIZE + "");
    }
}

3. 布局代码:

<?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="match_parent"
                android:background="#999999"
                android:orientation="vertical">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/sr_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:cacheColorHint="#00000000"
            android:divider="@null"
            android:dividerHeight="0dp"
            android:fadeScrollbars="false"
            android:listSelector="#00000000"
            android:scrollbars="vertical"/>

    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

4.List item 略.

以上代码,记录在这里, 留作以后。

原文链接:http://www.apkbus.com/blog-184446-78290.html



点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消