PullToRefresh下拉刷新 加载更多 详解 +示例

来源:互联网 发布:c语言 gbk转unicode 编辑:程序博客网 时间:2024/05/18 14:26
常用设置
项目地址:https://github.com/chrisbanes/Android-PullToRefresh

a. 设置刷新模式

  • 如果Mode设置成Mode.PULL_FROM_START或Mode.PULL_FROM_END,可以设置Listener为OnRefreshListener,并实现onRefresh()方法;当然此时也可以设置Listener为OnRefreshListener2,但是Mode设置成Mode.PULL_FROM_START的时候只调用onPullDownToRefresh()方法,Mode设置成Mode.PULL_FROM_END的时候只调用onPullUpToRefresh()方法,另一个方法是不会调用的。
  • 如果Mode设置成Mode.BOTH,需要设置Listener为OnRefreshListener2,并同时实现onPullDownToRefresh()、onPullUpToRefresh()两个回调方法,分别代表下拉、上拉时的操作;如果想上拉、下拉的时候做一样的操作,也可以设置Listener为OnRefreshListener,这样上拉下拉的时候都会调用onRefresh方法。
b. 设置上拉下拉中的提示文字内容 
      ILoadingLayout startLabels = pullToRefresh.getLoadingLayoutProxy(true, false);
  •  startLabels.setPullLabel("下拉刷新...");// 刚开始下拉时显示的提示   
  •  startLabels.setRefreshingLabel("正在载入...");// 正在刷新时显示的提示
  •  startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时显示的提示   
     ILoadingLayout endLabels = pullToRefresh.getLoadingLayoutProxy( false, true);
  •  endLabels.setPullLabel("上拉刷新...");// 刚开始上拉时显示的提示   
  •  endLabels.setRefreshingLabel("正在载入...");// 正在刷新时   
  •  endLabels.setReleaseLabel("放开刷新...");// 下拉达到一定距离时
c. 设置上拉下拉中文字的样式
    如果想要改动图标和文字的距离和布局,在这library项目下pull_to_refresh_header_horizontal.xml和pull_to_refresh_header_vertical.xml这两个文件中更改
     

d. 设置相关监听

  • setOnRefreshListener(OnRefreshListener listener) 设置刷新监听器;
  • setOnLastItemVisibleListener(OnLastItemVisibleListener listener) 设置是否到底部监听器,当用户拉到底时调用
  • setOnPullEventListener(OnPullEventListener listener) 设置事件监听器;
  • onRefreshComplete() 设置刷新完成监听器
  • setOnScrollListener() 设置滚动监听器
    • SCROLL_STATE_TOUCH_SCROLL 正在滚动
    • SCROLL_STATE_FLING 手指做了抛的动作(手指离开屏幕前,用力滑了一下)
    • SCROLL_STATE_IDLE  停止滚动
  • 传统的setOnClickListener和setOnTouchListener 


自定义的属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PullToRefresh">
        <!-- listview的背景色,不要设置A drawable to use as the background of the Refreshable View -->
        <attr name="ptrRefreshableViewBackground" format="reference|color" />
        <!-- 刷新布局的头、尾背景颜色A drawable to use as the background of the Header and Footer Loading Views -->
        <attr name="ptrHeaderBackground" format="reference|color" />
        <!-- 头、尾文字颜色Text Color of the Header and Footer Loading Views -->
        <attr name="ptrHeaderTextColor" format="reference|color" />
        <!-- 头、尾副文字如时间的颜色Text Color of the Header and Footer Loading Views Sub Header -->
        <attr name="ptrHeaderSubTextColor" format="reference|color" />
        <!-- 刷新模式,manualOnly为只允许手动触发 Mode of Pull-to-Refresh that should be used -->
        <attr name="ptrMode">
            <flag name="disabled" value="0x0" />
            <flag name="pullFromStart" value="0x1" />
            <flag name="pullFromEnd" value="0x2" />
            <flag name="both" value="0x3" />
            <flag name="manualOnly" value="0x4" />
            <!--废弃的 These last two are depreacted -->
            <flag name="pullDownFromTop" value="0x1" />
            <flag name="pullUpFromBottom" value="0x2" />
        </attr>
        <!-- 在listview滑动到底部或顶部时,是否显示拖动刷新提示图标 Whether the Indicator overlay(s) should be used -->
        <attr name="ptrShowIndicator" format="reference|boolean" />
        <!-- 设置刷新时的图标 Drawable to use as Loading Indicator. Changes both Header and Footer. -->
        <attr name="ptrDrawable" format="reference" />
        <!-- 刚开始下拉时的图片Drawable to use as Loading Indicator in the Header View. Overrides value set in ptrDrawable. -->
        <attr name="ptrDrawableStart" format="reference" />
        <!--刚开始上拉时的图片 Drawable to use as Loading Indicator in the Footer View. Overrides value set in ptrDrawable. -->
        <attr name="ptrDrawableEnd" format="reference" />
        <!--是否使用安卓内部的滚动 Whether Android's built-in Over Scroll should be utilised for Pull-to-Refresh. -->
        <attr name="ptrOverScroll" format="reference|boolean" />
        <!-- Base text color, typeface, size, and style for Header and Footer Loading Views -->
        <attr name="ptrHeaderTextAppearance" format="reference" />
        <!-- Base text color, typeface, size, and style for Header and Footer Loading Views Sub Header -->
        <attr name="ptrSubHeaderTextAppearance" format="reference" />
        <!-- 动画模式 Style of Animation should be used displayed when pulling. -->
        <attr name="ptrAnimationStyle">
            <flag name="rotate" value="0x0" />
            <flag name="flip" value="0x1" />
        </attr>
        <!-- 刷新时是否允许拖动 Whether the user can scroll while the View is Refreshing -->
        <attr name="ptrScrollingWhileRefreshingEnabled" format="reference|boolean" />
        <!--  Whether PullToRefreshListView has it's extras enabled. This allows the user to be 
            able to scroll while refreshing, and behaves better. It acheives this by adding
            Header and/or Footer Views to the ListView.  -->
        <attr name="ptrListViewExtrasEnabled" format="reference|boolean" />
        <!--下拉时图片是否继续旋转  Whether the Drawable should be continually rotated as you pull. This only
            takes effect when using the 'Rotate' Animation Style. -->
        <attr name="ptrRotateDrawableWhilePulling" format="reference|boolean" />
        <!--废弃了,不要使用 BELOW HERE ARE DEPRECEATED. DO NOT USE. -->
        <attr name="ptrAdapterViewBackground" format="reference|color" />
        <attr name="ptrDrawableTop" format="reference" />
        <attr name="ptrDrawableBottom" format="reference" />
    </declare-styleable>
</resources>


库中的原始布局

pull_to_refresh_header_vertical.xml

<?xml version="1.0" encoding="utf-8"?>

<merge xmlns:android="http://schemas.android.com/apk/res/android" >
    <FrameLayout
        android:id="@+id/fl_inner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/header_footer_top_bottom_padding"
        android:paddingLeft="@dimen/header_footer_left_right_padding"
        android:paddingRight="@dimen/header_footer_left_right_padding"
        android:paddingTop="@dimen/header_footer_top_bottom_padding" >
        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical" >
            <ImageView
                android:id="@+id/pull_to_refresh_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center" />
            <ProgressBar
                android:id="@+id/pull_to_refresh_progress"
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:indeterminate="true"
                android:visibility="visible" />
        </FrameLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center_horizontal"
            android:orientation="vertical" >
            <TextView
                android:id="@+id/pull_to_refresh_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text="我是描述信息"
                android:textAppearance="?android:attr/textAppearance"
                android:textStyle="bold" />
            <TextView
                android:id="@+id/pull_to_refresh_sub_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text="我是默认隐藏的描述信息,如显示时间"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:visibility="visible" />
        </LinearLayout>
    </FrameLayout>
</merge>



演示示例-ListView-布局
activity_main.xml
<RelativeLayout 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" >
    <com.handmark.pulltorefresh.library.PullToRefreshListView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/pull_refresh_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:divider="#19000000"
        android:dividerHeight="4dp"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:smoothScrollbar="true"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrListViewExtrasEnabled="false"
        ptr:ptrMode="both"
        ptr:ptrScrollingWhileRefreshingEnabled="true" />
</RelativeLayout>


演示示例-ListView-代码
public class PullToRefreshListActivity extends Activity {
    private LinkedList<String> mListItems;
    private PullToRefreshListView mPullRefreshListView;
    private ArrayAdapter<String> mAdapter;
    private int mItemCount = 20;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
        mPullRefreshListView.setMode(Mode.BOTH);
        initDatas();
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1mListItems);
        mPullRefreshListView.setAdapter(mAdapter);
        mPullRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //这里写下拉刷新的任务
                new GetDataTask().execute();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //这里写上拉加载更多的任务
                new GetDataTask().execute();
            }
        });
    }
    private void initDatas() {
        mListItems = new LinkedList<String>();
        for (int i = 0; i < mItemCount; i++) {
            mListItems.add("包青天 " + i);
        }
    }
    private class GetDataTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            SystemClock.sleep(1000);
            return "包青天-新 " + (mItemCount++);
        }
        @Override
        protected void onPostExecute(String result) {
            mListItems.add(result);
            mAdapter.notifyDataSetChanged();
            mPullRefreshListView.onRefreshComplete();
            //要先调用mPullToRefreshListView.getRefreshableView()获取真正的listview后才能使用某些listview的API
            mPullRefreshListView.getRefreshableView().setSelection(mItemCount);
        }
    }
}


演示示例-GridView-布局
activity_ptr_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <!--
通过horizontalSpacing设置列间距无效,实际会根据屏幕宽度和item的宽度自动得出间距
宽度设置为"wrap_content"时是match_parent的效果,可以通过padding和background观察到这种效果
高度必须设为"match_parent",否则增加item时高度不会自动增大 
android:numColumns="auto_fit" 将根据columnWidth和Spacing来自动计算,但是非常不好用
columnWidth:将剩余空间分摊给列;SpacingWidth:将剩余空间分摊给间隔空隙
    -->
    <com.handmark.pulltorefresh.library.PullToRefreshGridView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/pull_refresh_grid"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:background="#B4EEB4"
        android:gravity="center_horizontal"
        android:horizontalSpacing="1dp"
        android:numColumns="4"
        android:padding="5dp"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:verticalSpacing="1dp"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrDrawableStart="@drawable/ic_launcher"
        ptr:ptrHeaderBackground="#B2DFEE"
        ptr:ptrHeaderSubTextColor="#ff0000"
        ptr:ptrHeaderTextColor="#0000ff"
        ptr:ptrListViewExtrasEnabled="false"
        ptr:ptrMode="both"
        ptr:ptrRefreshableViewBackground="#f00"
        ptr:ptrScrollingWhileRefreshingEnabled="false"
        ptr:ptrShowIndicator="true" />
</LinearLayout>  

 grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_grid_item_text"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:background="#FFE4E1"
    android:gravity="center"
    android:textColor="#000"
    android:textSize="15sp" />


演示示例-GridView-代码
public class PullToRefreshGridActivity extends Activity {
    private LinkedList<String> mListItems;
    private PullToRefreshGridView mPullRefreshListView;
    private ArrayAdapter<String> mAdapter;
    private int mItemCount = 30;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptr_grid);
        mPullRefreshListView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
        initDatas();
        initIndicator();
        mAdapter = new ArrayAdapter<String>(this, R.layout.grid_item, R.id.id_grid_item_textmListItems);
        mPullRefreshListView.setAdapter(mAdapter);
        mPullRefreshListView.setOnRefreshListener(new MyOnRefreshListener());
    }
    private void initDatas() {
        mListItems = new LinkedList<String>();
        for (int i = 0; i < mItemCount; i++) {
            mListItems.add(i + "");
        }
    }
    private void initIndicator() {
        ILoadingLayout startLabels = mPullRefreshListView.getLoadingLayoutProxy(truefalse);
        startLabels.setPullLabel("你可劲拉,拉...");// 刚下拉时,显示的提示
        startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新时
        startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下来达到一定距离时,显示的提示
        ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(falsetrue);
        endLabels.setPullLabel("你可劲拉,拉2...");// 刚下拉时,显示的提示
        endLabels.setRefreshingLabel("好嘞,正在刷新2...");// 刷新时
        endLabels.setReleaseLabel("你敢放,我就敢刷新2...");// 下来达到一定距离时,显示的提示
    }
    private class MyOnRefreshListener implements OnRefreshListener2<GridView> {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {//下拉时更新时间
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd E aHH:mm:ss");
            String label = mSimpleDateFormat.format(new Date());
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            new GetDataTask().execute();
        }
        @Override
        public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {//上拉时不更新
            new GetDataTask().execute();
        }
    }
    private class GetDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            SystemClock.sleep(1000);//休息1秒,伪造正在刷新的样子
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            mListItems.add("新增 " + mItemCount++);//添加一条数据
            mAdapter.notifyDataSetChanged();//更新数据
            mPullRefreshListView.onRefreshComplete();//刷新完毕
        }
    }
}
0 0
原创粉丝点击