Android之下拉与上拉刷新

转载请注明出处:http://blog.csdn.net/loveyaozu/article/details/51240525

Android日常开发中,对于下拉与上拉刷新控件的使用非常之频繁。一般都会采用第三方库,但是下拉刷新做到简单优雅并不是太多,甚至有的兼容性都存在问题。这个是不能接受的。最近在github上面看到一位哥们提供的下拉刷新的库非常不错,非常简洁。所以今天把它推荐给大家,供大家日常开发使用。文章结尾会给大家提供Demo供各位下载参考使用。

Demo中一共提供四种下拉/上拉刷新。ListView的下拉/上拉刷新,GridView的下拉/上拉刷新,RecycleView的下拉/上拉刷新,SwipeRefreshLayout与ListView组合的下拉/上拉刷新。

Demo分为三个部分:RecycleView的jar包(之前RecycleView的包Google把它放在v7下面的,不知道为什么现在没有,所以单独放了一个RecycleViewjar包),第三方库CommonPullToRefresh_Lib(这个在实际开发中可以把它做成jar包,放到工程的libs下面),以及Demo工程。

工程目录结构:

从工程的目录结构中可以看到只有GridViewAtivity,ListViewActivity,MainActivity,RecyclerViewActivity,SwipeListViewActivity这五个Activity。其中MainActivity是启动界面,菜单列表。看上去没有什么额外的东西,相对还是比较简洁的。

activity_main.xml布局文件:

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center_horizontal"
    android:background="@android:color/white"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="goListView"
        android:textAllCaps="false"
        android:text="@string/listView_with_loadmore" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="goRecyclerView"
        android:text="@string/recyclerview_with_loadmore"
        android:textAllCaps="false" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="goGridView"
        android:text="@string/gridview_with_loadmore"
        android:textAllCaps="false" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:onClick="goSwipeListView"
        android:text="@string/swipe_listview_with_loadmore"
        android:textAllCaps="false" />

</LinearLayout>

MainActivity

package com.syz.pullrefresh;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

/**
 * @author syz
 * @date 2016-4-24
 */
public class MainActivity extends Activity {

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

    public void goListView(View view) {
        startActivity(new Intent(this, ListViewActivity.class));
    }

    public void goRecyclerView(View view) {
        startActivity(new Intent(this, RecyclerViewActivity.class));
    }

    public void goGridView(View view) {
        startActivity(new Intent(this, GridViewAtivity.class));
    }

    public void goSwipeListView(View view) {
        startActivity(new Intent(this, SwipeListViewActivity.class));
    }
}

效果图:

listview_layout.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="match_parent"
    android:orientation="vertical" >

    <com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout
        xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/test_list_view_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f0f0"
        cube_ptr:ptr_duration_to_close="200"
        cube_ptr:ptr_duration_to_close_header="700"
        cube_ptr:ptr_keep_header_when_refresh="true"
        cube_ptr:ptr_pull_to_fresh="false"
        cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
        cube_ptr:ptr_resistance="1.8" >

        <ListView
            android:id="@+id/test_list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="0.1dp"
            android:background="@android:color/white"
            android:divider="#b0b0b0"
            android:choiceMode="singleChoice"
            android:fadingEdge="none"
            android:scrollbarStyle="outsideOverlay" />
    </com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout>

</LinearLayout>

listitem_layout.xml布局:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@android:id/text1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:textAppearance="?android:attr/textAppearanceListItemSmall"
          android:gravity="center_vertical"
          android:textColor="@android:color/black"
          android:paddingStart="?android:attr/listPreferredItemPaddingStart"
          android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
          android:minHeight="?android:attr/listPreferredItemHeightSmall" />

ListViewActivity

/*
Copyright 2015 chanven

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package com.syz.pullrefresh;

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout;
import com.syz.commonpulltorefresh.lib.PtrDefaultHandler;
import com.syz.commonpulltorefresh.lib.PtrFrameLayout;
import com.syz.commonpulltorefresh.lib.loadmore.OnLoadMoreListener;

/**
 * ListView with loadmore
 *
 * @author syz
 * @date 2015-9-21
 */
public class ListViewActivity extends Activity {
    PtrClassicFrameLayout ptrClassicFrameLayout;
    ListView mListView;
    private List<String> mData = new ArrayList<String>();
    private ListViewAdapter mAdapter;
    Handler handler = new Handler();

    int page = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_layout);
        ptrClassicFrameLayout = (PtrClassicFrameLayout) this.findViewById(R.id.test_list_view_frame);
        mListView = (ListView) this.findViewById(R.id.test_list_view);
        initData();
    }

    private void initData() {
        mAdapter = new ListViewAdapter(this, mData);
        mListView.setAdapter(mAdapter);
        ptrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                ptrClassicFrameLayout.autoRefresh(true);
            }
        }, 150);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 0;
                        mData.clear();
                        for (int i = 0; i < 17; i++) {
                            mData.add(new String("  ListView item  ——" + i));
                        }
                        mAdapter.notifyDataSetChanged();
                        ptrClassicFrameLayout.refreshComplete();
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    }
                }, 1000);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mData.add(new String("  ListView item  - add " + page));
                        mAdapter.notifyDataSetChanged();
                        ptrClassicFrameLayout.loadMoreComplete(true);
                        page++;
                        Toast.makeText(ListViewActivity.this, "load more complete", Toast.LENGTH_SHORT)
                                .show();
                    }
                }, 1000);
            }
        });
    }

    public class ListViewAdapter extends BaseAdapter {
        private List<String> datas;
        private LayoutInflater inflater;

        public ListViewAdapter(Context context, List<String> data) {
            super();
            inflater = LayoutInflater.from(context);
            datas = data;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.listitem_layout, parent, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(datas.get(position));
            return convertView;
        }

        public List<String> getData() {
            return datas;
        }

    }

}

效果图:

girdview_layout.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="match_parent"
    android:orientation="vertical" >

    <com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout
        xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/test_grid_view_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f0f0"
        cube_ptr:ptr_duration_to_close="200"
        cube_ptr:ptr_duration_to_close_header="700"
        cube_ptr:ptr_keep_header_when_refresh="true"
        cube_ptr:ptr_pull_to_fresh="false"
        cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
        cube_ptr:ptr_resistance="1.8" >

        <com.syz.commonpulltorefresh.lib.loadmore.GridViewWithHeaderAndFooter
            android:id="@+id/test_grid_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="0.1dp"
            android:background="@android:color/white"
            android:divider="#b0b0b0"
            android:choiceMode="singleChoice"
            android:fadingEdge="none"
            android:numColumns="4"
            android:scrollbarStyle="outsideOverlay" />
    </com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout>

</LinearLayout>

GridViewAtivity

/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package com.syz.pullrefresh;

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout;
import com.syz.commonpulltorefresh.lib.PtrDefaultHandler;
import com.syz.commonpulltorefresh.lib.PtrFrameLayout;
import com.syz.commonpulltorefresh.lib.loadmore.GridViewWithHeaderAndFooter;
import com.syz.commonpulltorefresh.lib.loadmore.OnLoadMoreListener;

/**
 * GridView with loadmore
 *
 * @author syz
 * @date 2015-10-13
 */
public class GridViewAtivity extends Activity {
    PtrClassicFrameLayout ptrClassicFrameLayout;
    GridViewWithHeaderAndFooter mGridView;
    GridViewAdapter mAdapter;
    private List<String> mData = new ArrayList<String>();
    Handler handler = new Handler();

    int page = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.girdview_layout);
        ptrClassicFrameLayout = (PtrClassicFrameLayout) this.findViewById(R.id.test_grid_view_frame);
        mGridView = (GridViewWithHeaderAndFooter) this.findViewById(R.id.test_grid_view);
        initData();
    }

    private void initData() {
        mAdapter = new GridViewAdapter(this, mData);
        mGridView.setAdapter(mAdapter);
        ptrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                ptrClassicFrameLayout.autoRefresh(true);
            }
        }, 150);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 0;
                        mData.clear();
                        for (int i = 0; i < 40; i++) {
                            mData.add(new String("GridView item  ——" + i));
                        }
                        mAdapter.notifyDataSetChanged();
                        ptrClassicFrameLayout.refreshComplete();
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    }
                }, 1000);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        for (int i = 0; i < 4; i++) {
                            mData.add(new String("GridView item -- add" + page));
                        }
                        mAdapter.notifyDataSetChanged();
                        ptrClassicFrameLayout.loadMoreComplete(true);
                        page++;
                        Toast.makeText(GridViewAtivity.this, "load more complete", Toast.LENGTH_SHORT)
                                .show();
                    }
                }, 1000);
            }
        });
    }

    public class GridViewAdapter extends BaseAdapter {
        private List<String> datas;
        private LayoutInflater inflater;

        public GridViewAdapter(Context context, List<String> data) {
            super();
            inflater = LayoutInflater.from(context);
            datas = data;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.listitem_layout, parent, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(datas.get(position));
            return convertView;
        }

        public List<String> getData() {
            return datas;
        }

    }
}

效果图:

recyclerview_layout.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="match_parent"
    android:orientation="vertical" >

    <com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout
        xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/test_recycler_view_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f0f0"
        cube_ptr:ptr_duration_to_close="200"
        cube_ptr:ptr_duration_to_close_header="700"
        cube_ptr:ptr_keep_header_when_refresh="true"
        cube_ptr:ptr_pull_to_fresh="false"
        cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
        cube_ptr:ptr_resistance="1.8" >

        <android.support.v7.widget.RecyclerView
            android:id="@+id/test_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"/>
    </com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout>

</LinearLayout>

RecyclerViewActivity

/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package com.syz.pullrefresh;

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout;
import com.syz.commonpulltorefresh.lib.PtrDefaultHandler;
import com.syz.commonpulltorefresh.lib.PtrFrameLayout;
import com.syz.commonpulltorefresh.lib.loadmore.OnLoadMoreListener;
import com.syz.commonpulltorefresh.lib.recyclerview.RecyclerAdapterWithHF;

/**
 * RecyclerView with loadmore
 *
 * @author syz
 * @date 2015-9-21
 */
public class RecyclerViewActivity extends Activity {
    PtrClassicFrameLayout ptrClassicFrameLayout;
    RecyclerView mRecyclerView;
    private List<String> mData = new ArrayList<String>();
    private RecyclerAdapter adapter;
    private RecyclerAdapterWithHF mAdapter;
    Handler handler = new Handler();

    int page = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview_layout);

        ptrClassicFrameLayout = (PtrClassicFrameLayout) this.findViewById(R.id.test_recycler_view_frame);
        mRecyclerView = (RecyclerView) this.findViewById(R.id.test_recycler_view);
        init();
    }

    private void init() {
        adapter = new RecyclerAdapter(this, mData);
        mAdapter = new RecyclerAdapterWithHF(adapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mAdapter);
        ptrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                ptrClassicFrameLayout.autoRefresh(true);
            }
        }, 150);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 0;
                        mData.clear();
                        for (int i = 0; i < 17; i++) {
                            mData.add(new String("  RecyclerView item  ——" + i));
                        }
                        mAdapter.notifyDataSetChanged();
                        ptrClassicFrameLayout.refreshComplete();
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    }
                }, 2000);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mData.add(new String("  RecyclerView item  - add " + page));
                        mAdapter.notifyDataSetChanged();
                        ptrClassicFrameLayout.loadMoreComplete(true);
                        page++;
                        Toast.makeText(RecyclerViewActivity.this, "load more complete", Toast.LENGTH_SHORT)
                                .show();
                    }
                }, 1000);
            }
        });
    }

    public class RecyclerAdapter extends Adapter<ViewHolder> {
        private List<String> datas;
        private LayoutInflater inflater;

        public RecyclerAdapter(Context context, List<String> data) {
            super();
            inflater = LayoutInflater.from(context);
            datas = data;
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            ChildViewHolder holder = (ChildViewHolder) viewHolder;
            holder.itemTv.setText(datas.get(position));
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewHolder, int position) {
            View view = inflater.inflate(R.layout.listitem_layout, null);
            return new ChildViewHolder(view);
        }

    }

    public class ChildViewHolder extends ViewHolder {
        public TextView itemTv;

        public ChildViewHolder(View view) {
            super(view);
            itemTv = (TextView) view;
        }

    }
}

效果图:

swipe_listview_layout.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="match_parent"
    android:orientation="vertical">

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

        <ListView
            android:id="@+id/lv_swipe_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="0.1dp"
            android:background="@android:color/white"
            android:divider="#b0b0b0"
            android:choiceMode="singleChoice"
            android:fadingEdge="none"
            android:scrollbarStyle="outsideOverlay" />

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

</LinearLayout>

SwipeListViewActivity

package com.syz.pullrefresh;

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

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.syz.commonpulltorefresh.lib.loadmore.OnLoadMoreListener;
import com.syz.commonpulltorefresh.lib.loadmore.SwipeRefreshHelper;
import com.syz.commonpulltorefresh.lib.loadmore.SwipeRefreshHelper.OnSwipeRefreshListener;

/**
 * listView with load more in swipeRefreshLayout
 * Created by syz on 2015-11-5.
 */
public class SwipeListViewActivity extends Activity{
    private SwipeRefreshLayout mSryt;
    private ListView mListView;

    private List<String> mDatas = new ArrayList<String>();
    private ListViewAdapter mAdapter;
    private SwipeRefreshHelper mSwipeRefreshHelper;

    private int page = 0;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe_listview_layout);
        initView();
        initData();
    }

    private void initView() {
        mSryt = (SwipeRefreshLayout) this.findViewById(R.id.sryt_swipe_listview);
        mListView = (ListView) findViewById(R.id.lv_swipe_listview);
        mSryt.setColorSchemeColors(Color.BLUE);
    }

    private void initData() {
        mAdapter = new ListViewAdapter(this, mDatas);
        mListView.setAdapter(mAdapter);
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSryt);

        mSryt.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshHelper.autoRefresh();
            }
        });

        mSwipeRefreshHelper.setOnSwipeRefreshListener(new OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mDatas.clear();
                        page = 0;
                        for (int i = 0; i < 17; i++) {
                            mDatas.add(new String("  SwipeListView item  ——" + i));
                        }
                        mAdapter.notifyDataSetChanged();
                        mSwipeRefreshHelper.refreshComplete();
                        mSwipeRefreshHelper.setLoadMoreEnable(true);
                    }
                }, 1000);
            }
        });

        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mDatas.add(new String("  SwipeListView item  - add " + page));
                        mAdapter.notifyDataSetChanged();
                        mSwipeRefreshHelper.loadMoreComplete(true);
                        page++;
                        Toast.makeText(SwipeListViewActivity.this, "load more complete", Toast.LENGTH_SHORT)
                                .show();
                    }
                }, 1000);
            }
        });

    }

    OnSwipeRefreshListener mOnSwipeRefreshListener = new OnSwipeRefreshListener() {
        @Override
        public void onfresh() {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mDatas.clear();
                    page = 0;
                    for (int i = 0; i < 17; i++) {
                        mDatas.add(new String("  SwipeListView item  -" + i));
                    }
                    mAdapter.notifyDataSetChanged();
                    mSwipeRefreshHelper.refreshComplete();
                    mSwipeRefreshHelper.setLoadMoreEnable(true);
                }
            }, 1000);
        }
    };

    public class ListViewAdapter extends BaseAdapter {
        private List<String> datas;
        private LayoutInflater inflater;

        public ListViewAdapter(Context context, List<String> data) {
            super();
            inflater = LayoutInflater.from(context);
            datas = data;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.listitem_layout, parent, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(datas.get(position));
            return convertView;
        }

        public List<String> getData() {
            return datas;
        }

    }
}

效果图:

配置

有6个参数可配置:

阻尼系数

默认: 1.7f,越大,感觉下拉时越吃力。 mPtrFrame.setResistance(1.7f)

触发刷新时移动的位置比例

默认,1.2f,移动达到头部高度1.2倍时可触发刷新操作。 mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f)

回弹延时

默认 200ms,回弹到刷新高度所用时间。 mPtrFrame.setDurationToClose(200)

头部回弹时间

默认1000ms。 mPtrFrame.setDurationToCloseHeader(1000)

刷新是保持头部

默认值 true。 mPtrFrame.setKeepHeaderWhenRefresh(true)

下拉刷新 / 释放刷新

默认为释放刷新,即false。 mPtrFrame.setPullToRefresh(false)

除此之外也可以在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="match_parent"
    android:orientation="vertical">

    <com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout
        android:id="@+id/test_list_view_frame"
        xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f0f0"
        cube_ptr:ptr_resistance="1.7"
        cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
        cube_ptr:ptr_duration_to_close="200"
        cube_ptr:ptr_duration_to_close_header="1000"
        cube_ptr:ptr_keep_header_when_refresh="true"
        cube_ptr:ptr_pull_to_fresh="false">

        <ListView
            android:id="@+id/test_list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white"
            android:choiceMode="singleChoice"
            android:divider="#b0b0b0"
            android:dividerHeight="0.1dp"
            android:fadingEdge="none"
            android:scrollbarStyle="outsideOverlay"/>
    </com.syz.commonpulltorefresh.lib.PtrClassicFrameLayout>

</LinearLayout>

Demo下载地址:http://download.csdn.net/detail/loveyaozu/9501643

参考:https://github.com/Chanven/CommonPullToRefresh

时间: 2024-10-25 22:05:21

Android之下拉与上拉刷新的相关文章

android自定义控件之ListView上拉加载与下拉刷新

自定义控件LoadLayout import android.content.Context; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import andr

手机影音第十三天,xutils3、Glide的使用获取网络图片;下拉、上滑刷新;缓存网络资源

代码已经托管到码云上,感兴趣的小伙伴可以下载看看 https://git.oschina.net/joy_yuan/MobilePlayer 本次的网络资源地址使用的是时光网的api接口,地址如下: http://api.m.mtime.cn/PageSubArea/TrailerList.api 效果如下: 一.Xutils3 的使用 去github上看详解:https://github.com/wyouflf/xUtils3 xUtils3简介 xUtils 包含了orm, http(s),

android自定义控件之ListView上拉加载

自定义控件LoadLayout import android.content.Context; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import andr

Android 自定义仿IOS上拉菜单实现

最近在做一个歪果仁给我外包的项目,主页需要做一个类似于IOS那种上拉菜单的功能,于是一时间试了各种方法,什么Spinner.Drawlayout,SlidingMenu等等等等,都搞不了,后面实在被逼无奈自己写了一个上拉菜单控件,居然还能凑合着用! 姑且可以叫他MyPullUpMenu! 有时间我会封装一下发到GitHub. 效果图如下: 实现的功能有仨: 1.上拉位置未超过一定距离时,松开自动往下滚动. 2.上拉位置超过一定距离时,松开自动网上滚动直至菜单全展开. 3.菜单滚动到顶部并停止滚动

android 自定义scrollview 仿QQ空间效果 下拉伸缩顶部图片,上拉回弹 上拉滚动顶部title 颜色渐变

首先要知道  自定义scrollview 仿QQ效果 下拉伸缩放大顶部图片 的原理是监听ontouch事件,在MotionEvent.ACTION_MOVE事件时候,使用不同倍数的系数,重置布局位置[注此处是伸缩隐藏,不是同比例放大] inner.layout(normal.left, (int) (normal.top + inner_move_H), normal.right, (int) (normal.bottom + inner_move_H)); 关于“自定义scrollview 仿

iOSTableview 禁止下拉,允许上拉

1 回弹机制:bounces alwaysBounceHorizontal alwaysBounceVerticalbounces:描述的当scrollview的显示超过内容区域的边缘以及返回时,是否有弹性,默认值为YES.值为YES的时候,意味着到达contentSize所描绘的的边界的时候,拖动会产生弹性.值为No的时候,拖动到达边界时,会立即停止.所以,如果在上面的例子当中,将bounces设置为NO时,窗口中是不会显示contentSize范围外的内容的. -(void)scrollVi

tabBar 的上拉隐藏,上拉显示实现

PushListView.h @interface PushListView : UIView<UITableViewDelegate,UITableViewDataSource { CGFloat contentOffsetY; CGFloat oldContentOffsetY; CGFloat newContentOffsetY; } ............................... PushListView.m //开始拖拽视图 - (void)scrollViewWill

自个儿写Android的下拉刷新/上拉加载控件 (续)

本文算是对之前的一篇博文<自个儿写Android的下拉刷新/上拉加载控件>的续章,如果有兴趣了解更多的朋友可以先看一看之前的这篇博客. 事实上之所以会有之前的那篇博文的出现,是起因于前段时间自己在写一个练手的App时很快就遇到这种需求.其实我们可以发现类似这样下拉刷新.上拉加载的功能正在变得越来越普遍,可以说如今基本上绝大多数的应用里面都会使用到.当然,随着Android的发展,已经有不少现成的可以实现这种需求的"轮子"供我们使用了. 但转过头想一下想,既然本来就是自己练手

android 下拉刷新/上拉加载更多【pull-to-refresh】

这两天在做一个功能,需要用到"下拉刷新和上拉加载更多"这样的功能,开始的时候以为都是自己用控件加以控件来完成的,后来,在网上找了好长时间,发现直接可以用别人的现在的 library . 引用别人的library后直接就可以用的,只是注意一些细节就可以了. 我用的是pull to refresh (很多人都说这个比较好点). 它支持多种常用的需要刷新的View类型,如:ListView.ExpandableListView.GridView.WebView等.这里就给个下载地址吧:htt