PullToRefresh下拉刷新 加载更多 详解 +示例_pull_to_refresh-程序员宅基地

技术标签: Android Studio  Android  

常用设置
项目地址: 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();//刷新完毕
        }
    }
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xqkillua/article/details/53504653

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签