PullToRefresh(ListView 、GridView 、WebView)

基本上每个安卓项目里面都有PullToRefresh的使用,然后我到网上去找了相关知识,很多都不全面,不详细,缺东缺西,然后我就到网上博客里面到处找,更具自己项目里面的使用,把PullToRefreshListView PullToRefreshGridView PullToRefreshWebView总结起开,方便大家更好理解和使用,不废话,just do it.先把项目目录的图片给出来

第一步、把PullToRefresh项目的library导入android studio

到git hub上面去找,https://github.com/chrisbanes/Android-PullToRefresh,下载后把library文件夹加到自己的项目里面,然后改名改gradle配置

这个地方要注意了,记得compileSdkVersion 和buildToolsVersion版本和自己项目里面的一致,不然会编译出错,如果不知道怎么配置的话,我有一篇文章Android之SlidingMenu里面可有类似的配置,可以对比学习下,有益于以后从gitHub里面找项目用到自己的项目上。

第二步、实现PullToRefreshListView

1、下拉刷新


首先,我们先写第一个布局文件activity_main_bylistview.xml,用法和listView差不多。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:ptr="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity">    <com.handmark.pulltorefresh.library.PullToRefreshListView        ptr:ptrAnimationStyle="flip"        ptrHeaderBackground="#ff00ff"        ptrHeaderTextColor="#ddff34"        ptrRefreshableViewBackground="#44ff33"        android:id="@+id/pull_refresh_list"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:divider="#19000000"        android:cacheColorHint="#00000000"        android:layout_alignParentTop="true"        android:dividerHeight="2dp"        android:fadingEdge="none"        android:fastScrollEnabled="false"        android:footerDividersEnabled="false"        android:headerDividersEnabled="false"        android:smoothScrollbar="true"        >    </com.handmark.pulltorefresh.library.PullToRefreshListView></RelativeLayout>

因为和Listview差不多,所以需要适配器,这里我选择的是SimpleAdapter,然后我们需要写适配器的配置文件

simple_list_item_2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <TextView        android:id="@+id/text1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:textColor="#ffaaff"        android:textSize="25sp"        />    <TextView        android:id="@+id/text2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:textColor="#ffaaff"        android:textSize="25sp"        /></LinearLayout>

然后就是我们的MainActivity.java文件

package com.example.chenyu.pulltorefresh;import android.content.Intent;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Button;import android.widget.GridView;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.handmark.pulltorefresh.library.ILoadingLayout;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshGridView;import com.handmark.pulltorefresh.library.PullToRefreshListView;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List;import java.util.Map;public class MainActivity extends AppCompatActivity {    private PullToRefreshListView  lv;    private String[] mListTitle={"姓名: ","性别: ","年龄: ","居住地: ","邮箱: "};    private String[] mListStr={"chenyu","男","25","北京","2657607916@qq.com"};    private ListView mlistView=null;    private int i=0;    private SimpleAdapter adapter;    private Button button;    List<Map<String,Object>> mData=new ArrayList<Map<String,Object>>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main_bylistview);        lv= (PullToRefreshListView)findViewById(R.id.pull_refresh_list);        mData=getmData();        adapter=new SimpleAdapter(this,mData,R.layout.simple_list_item_2,new String[]{"title","text"},new int[]{R.id.text1,R.id.text2});        lv.setAdapter(adapter);        initIndicator();        //刷新监听事件        lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>(){            @Override            public void onRefresh(PullToRefreshBase<ListView> refreshView) {                // 模拟加载任务                new GetDataTask().execute();                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String label=simpleDateFormat.format(System.currentTimeMillis());                // 显示最后更新的时间                refreshView.getLoadingLayoutProxy()                        .setLastUpdatedLabel(label);            }        });    }    //初始化那个下拉和上拉要显示的文字    private void initIndicator()    {        ILoadingLayout startLabels = lv                .getLoadingLayoutProxy(true, false);        startLabels.setPullLabel("就把我往死里面拉吧...");// 刚下拉时,显示的提示        startLabels.setRefreshingLabel("正在刷新...");// 刷新时        startLabels.setReleaseLabel("放了我,我就刷新...");// 下来达到一定距离时,显示的提示        ILoadingLayout endLabels = lv.getLoadingLayoutProxy(                false, true);        endLabels.setPullLabel("就把我往死里面拉吧123...");// 刚下拉时,显示的提示        endLabels.setRefreshingLabel("正在刷新123...");// 刷新时        endLabels.setReleaseLabel("放了我,我就刷新123...");// 下来达到一定距离时,显示的提示    }    public List<Map<String,Object>> getmData(){        for(int i=0;i<mListTitle.length;i++){            Map<String,Object> map=new HashMap<String,Object>();            map.put("title",mListTitle[i]);            map.put("text",mListStr[i]);            mData.add(map);        }        return mData;    }    private class GetDataTask extends AsyncTask<Void, Void, Map<String,Object>>    {        @Override        protected Map<String, Object> doInBackground(Void... params) {            Map<String,Object> map=new HashMap<String,Object>();            //如果这个地方不使用线程休息的话,刷新就不会显示在那个PullToRefreshListView的UpdatedLabel上面            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }            map.put("title","title"+(i++)+":--->");            map.put("text", "text" + (i++));            //加入数据,这里是可以的//          mData.add(map);            return map;        }        @Override        protected void onPostExecute(Map<String, Object> stringObjectMap) {            //            super.onPostExecute(stringObjectMap);            mData.add(stringObjectMap);            adapter.notifyDataSetChanged();//更新数据            // Call onRefreshComplete when the list has been refreshed. 如果没有下面的函数那么刷新将不会停            lv.onRefreshComplete();        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}
就会产生这样的效果


在这个MainActivity.java类里面有我用的

 lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>()

监听,其实在这里还有一个监听,这个监听支持下拉,但是不支持上拉,

2、然后我们来实现支持上拉


首先在activity_main_bylistview.xml这个布局文件里面 我们添加了一个属性:ptr:ptrMode="both" ,意思:上拉和下拉都支持,一定要记得写上这个属性,不然等下我们下拉没反应。 可选值为:disabled(禁用下拉刷新),pullFromStart(仅支持下拉刷新),pullFromEnd(仅支持上拉刷新),both(二者都支持),manualOnly(只允许手动触发) 当然了,如果你不喜欢在布局文件中指定,完全可以使用代码设置,在onCreate里面写:mPullRefreshListView.setMode(Mode.BOTH);//设置你需要的模式
然后在MainActivity.java类里面用第一个监听lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>()
接下来的MainActivity.java文件
package com.example.chenyu.pulltorefresh;import android.content.Intent;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Button;import android.widget.GridView;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.handmark.pulltorefresh.library.ILoadingLayout;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshGridView;import com.handmark.pulltorefresh.library.PullToRefreshListView;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.List;import java.util.Map;public class MainActivity extends AppCompatActivity {    private PullToRefreshListView  lv;    private String[] mListTitle={"姓名: ","性别: ","年龄: ","居住地: ","邮箱: "};    private String[] mListStr={"chenyu","男","25","北京","2657607916@qq.com"};    private ListView mlistView=null;    private int i=0;    private SimpleAdapter adapter;    private Button button;    List<Map<String,Object>> mData=new ArrayList<Map<String,Object>>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main_bylistview);        lv= (PullToRefreshListView)findViewById(R.id.pull_refresh_list);        mData=getmData();        adapter=new SimpleAdapter(this,mData,R.layout.simple_list_item_2,new String[]{"title","text"},new int[]{R.id.text1,R.id.text2});        lv.setAdapter(adapter);        initIndicator();        //刷新监听事件        lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>(){            @Override            public void onRefresh(PullToRefreshBase<ListView> refreshView) {                // 模拟加载任务                new GetDataTask().execute();                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String label=simpleDateFormat.format(System.currentTimeMillis());                // 显示最后更新的时间                refreshView.getLoadingLayoutProxy()                        .setLastUpdatedLabel(label);            }        });        //下拉刷新 上拉加载        lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {            @Override            public void onPullDownToRefresh(PullToRefreshBase refreshView) {                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String label = simpleDateFormat.format(System.currentTimeMillis());                Toast.makeText(MainActivity.this, "PullDownRefresh", Toast.LENGTH_SHORT).show();                new GetDataTask().execute();                // 显示最后更新的时间                refreshView.getLoadingLayoutProxy()                        .setLastUpdatedLabel(label);            }            @Override            public void onPullUpToRefresh(PullToRefreshBase refreshView) {                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String label = simpleDateFormat.format(System.currentTimeMillis());                Toast.makeText(MainActivity.this, "PullUpToRefresh", Toast.LENGTH_SHORT).show();                new GetDataTask().execute();                // 显示最后更新的时间                refreshView.getLoadingLayoutProxy()                        .setLastUpdatedLabel(label);                //下拉功能演示完之后,这个地方是跳到GridView界面去//                Intent intent = new Intent(MainActivity.this, GridActivity.class);//                startActivity(intent);            }        });    }    //初始化那个下拉和上拉要显示的文字    private void initIndicator()    {        ILoadingLayout startLabels = lv                .getLoadingLayoutProxy(true, false);        startLabels.setPullLabel("就把我往死里面拉吧...");// 刚下拉时,显示的提示        startLabels.setRefreshingLabel("正在刷新...");// 刷新时        startLabels.setReleaseLabel("放了我,我就刷新...");// 下来达到一定距离时,显示的提示        ILoadingLayout endLabels = lv.getLoadingLayoutProxy(                false, true);        endLabels.setPullLabel("就把我往死里面拉吧123...");// 刚下拉时,显示的提示        endLabels.setRefreshingLabel("正在刷新123...");// 刷新时        endLabels.setReleaseLabel("放了我,我就刷新123...");// 下来达到一定距离时,显示的提示    }    public List<Map<String,Object>> getmData(){        for(int i=0;i<mListTitle.length;i++){            Map<String,Object> map=new HashMap<String,Object>();            map.put("title",mListTitle[i]);            map.put("text",mListStr[i]);            mData.add(map);        }        return mData;    }    private class GetDataTask extends AsyncTask<Void, Void, Map<String,Object>>    {        @Override        protected Map<String, Object> doInBackground(Void... params) {            Map<String,Object> map=new HashMap<String,Object>();            //如果这个地方不使用线程休息的话,刷新就不会显示在那个PullToRefreshListView的UpdatedLabel上面            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }            map.put("title","title"+(i++)+":--->");            map.put("text", "text" + (i++));            //加入数据,这里是可以的//          mData.add(map);            return map;        }        @Override        protected void onPostExecute(Map<String, Object> stringObjectMap) {            //            super.onPostExecute(stringObjectMap);            mData.add(stringObjectMap);            //更新数据            adapter.notifyDataSetChanged();            // Call onRefreshComplete when the list has been refreshed. 如果没有下面的函数那么刷新将不会停            lv.onRefreshComplete();        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

就会有下面的效果图


如果你的上拉和下拉需求是执行一样的代码,那么你可以继续注册OnRefreshListener接口,上拉和下拉都会执行同一个方法。

第三步、实现PullToRefreshGridView

先写布局文件 activity_main_bygridview.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:ptr="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity">    <com.handmark.pulltorefresh.library.PullToRefreshGridView        android:id="@+id/pull_refresh_grid"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:columnWidth="100dp"        android:gravity="center_horizontal"        android:horizontalSpacing="1dp"        android:numColumns="auto_fit"        android:stretchMode="columnWidth"        android:verticalSpacing="1dp"        ptr:ptrDrawable="@drawable/ic_launcher"        ptr:ptrMode="both"        >    </com.handmark.pulltorefresh.library.PullToRefreshGridView  ></RelativeLayout>
然后再写griditem.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="100dp"    android:gravity="center"    android:textColor="#ffffff"    android:textSize="16sp"    android:background="#000000"    android:layout_height="100dp" />  
我是通过Activity跳转过来的,在我们的那个MainActivity.java文件里面把那个上拉刷新执行的任务注释掉,然后就跳到了GridActivity.java类去了,记得要在AndroidManifest.xml里面配置Activity
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.chenyu.pulltorefresh" >    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity android:name=".GridActivity"                  android:icon="@drawable/ic_launcher"                  android:label="gridView"></activity>        <activity android:name=".WebViewActivity"            android:icon="@drawable/ic_launcher"            android:label="webView"></activity>        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.INTERNET" /></manifest>

            @Override            public void onPullUpToRefresh(PullToRefreshBase refreshView) { //               SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //               String label = simpleDateFormat.format(System.currentTimeMillis()); //               Toast.makeText(MainActivity.this, "PullUpToRefresh", Toast.LENGTH_SHORT).show(); //               new GetDataTask().execute();                // 显示最后更新的时间 //               refreshView.getLoadingLayoutProxy() //                       .setLastUpdatedLabel(label);                //下拉功能演示完之后,这个地方是跳到GridView界面去                Intent intent = new Intent(MainActivity.this, GridActivity.class);                startActivity(intent);            }

然后就是我们的GridActivity.java文件
package com.example.chenyu.pulltorefresh;import android.content.Intent;import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.widget.ArrayAdapter;import android.widget.GridView;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshGridView;import com.handmark.pulltorefresh.library.PullToRefreshListView;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;public class GridActivity extends AppCompatActivity {    private LinkedList<String> mListItems;    private PullToRefreshGridView mPullRefreshListView;    private ArrayAdapter<String> mAdapter;    private int mItemCount = 10;    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main_bygridview);        // 得到控件        mPullRefreshListView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);        // 初始化数据和数据源        initDatas();        mAdapter = new ArrayAdapter<String>(this, R.layout.griditem,                R.id.id_grid_item_text, mListItems);        mPullRefreshListView.setAdapter(mAdapter);        mPullRefreshListView                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>()                {                    @Override                    public void onPullDownToRefresh(                            PullToRefreshBase<GridView> refreshView)                    {                       // 显示最后更新的时间                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                        String label=simpleDateFormat.format(System.currentTimeMillis());                         refreshView.getLoadingLayoutProxy()                        .setLastUpdatedLabel(label);                        new GetDataTask().execute();                    }                    @Override                    public void onPullUpToRefresh(                            PullToRefreshBase<GridView> refreshView)                    {                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                        String label=simpleDateFormat.format(System.currentTimeMillis());                        refreshView.getLoadingLayoutProxy()                                .setLastUpdatedLabel(label);                        new GetDataTask().execute();                        //下拉功能演示完之后,这个地方是跳到GridView界面去//                        Intent intent = new Intent(GridActivity.this, WebViewActivity.class);//                        startActivity(intent);                    }                });    }    private void initDatas()    {        mListItems = new LinkedList<String>();        for (int i = 0; i < mItemCount; i++)        {            mListItems.add(i + "");        }    }    private class GetDataTask extends AsyncTask<Void, Void, Void>    {        @Override        protected Void doInBackground(Void... params)        {            try            {                Thread.sleep(3000);            } catch (InterruptedException e)            {            }            return null;        }        @Override        protected void onPostExecute(Void result)        {            mListItems.add("" + mItemCount++);            mAdapter.notifyDataSetChanged();            // Call onRefreshComplete when the list has been refreshed.            mPullRefreshListView.onRefreshComplete();        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

当我们PullToRefreshListView上拉的时候就跳到了PullToRefreshGridView去了 就有如下图的效果



拉刷新的转圈的图片咋变成机器人了
那是因为设置了
<com.handmark.pulltorefresh.library.PullToRefreshGridView         ptr:ptrDrawable="@drawable/ic_launcher"         ...         /> 
当然了这是旋转的效果,一般常用的还有,一个箭头倒置的效果,其实也很简单,一个属性:

ptr:ptrAnimationStyle="flip"

去掉ptr:ptrDrawable="@drawable/ic_launcher"这个属性,如果你希望用下图默认的箭头,你也可以自定义。

自定义下拉指示器文本内容等效果

可以在初始化完成mPullRefreshListView后,通过mPullRefreshListView.getLoadingLayoutProxy()可以得到一个ILoadingLayout对象,这个对象可以设置各种指示器中的样式、文本等。

如果你比较细心,会发现,前面我们设置上次刷新时间已经用到了:

// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

默认是上拉和下拉的字同时改变的,如果我希望单独改变呢?

    private void initIndicator()    {        ILoadingLayout startLabels = lv                .getLoadingLayoutProxy(true, false);        startLabels.setPullLabel("就把我往死里面拉吧...");// 刚下拉时,显示的提示        startLabels.setRefreshingLabel("正在刷新...");// 刷新时        startLabels.setReleaseLabel("放了我,我就刷新...");// 下来达到一定距离时,显示的提示        ILoadingLayout endLabels = lv.getLoadingLayoutProxy(                false, true);        endLabels.setPullLabel("就把我往死里面拉吧123...");// 刚下拉时,显示的提示        endLabels.setRefreshingLabel("正在刷新123...");// 刷新时        endLabels.setReleaseLabel("放了我,我就刷新123...");// 下来达到一定距离时,显示的提示    }
mPullRefreshListView.getLoadingLayoutProxy(true, false);接收两个参数,为true,false返回设置下拉的ILoadingLayout;为false,true返回设置上拉的。

常用的一些属性

当然了,pull-to-refresh在xml中还能定义一些属性:

ptrMode,ptrDrawable,ptrAnimationStyle这三个上面已经介绍过。

ptrRefreshableViewBackground 设置整个mPullRefreshListView的背景色

ptrHeaderBackground 设置下拉Header或者上拉Footer的背景色

ptrHeaderTextColor 用于设置Header与Footer中文本的颜色

ptrHeaderSubTextColor 用于设置Header与Footer中上次刷新时间的颜色

ptrShowIndicator如果为true会在mPullRefreshListView中出现icon,右上角和右下角,挺有意思的。

ptrHeaderTextAppearance ,ptrSubHeaderTextAppearance分别设置拉Header或者上拉Footer中字体的类型颜色等等。

ptrRotateDrawableWhilePulling当动画设置为rotate时,下拉是是否旋转。

ptrScrollingWhileRefreshingEnabled刷新的时候,是否允许ListView或GridView滚动。觉得为true比较好。

ptrListViewExtrasEnabled 决定了Header,Footer以何种方式加入mPullRefreshListView,true为headView方式加入,就是滚动时刷新头部会一起滚动。


第四步、实现PullToRefreshWebView

同样的道理,我是使用PullToRefreshGridView上拉跳到,PullToRefreshWebView的,把GridActivity.java里面改成下面这样,一开始那个AndroidManifest.xml文件已经配置好了,就可以直接跳到GrieView里面去了

                    public void onPullUpToRefresh(                            PullToRefreshBase<GridView> refreshView)                    {//                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//                        String label=simpleDateFormat.format(System.currentTimeMillis());//                        refreshView.getLoadingLayoutProxy()//                                .setLastUpdatedLabel(label);//                        new GetDataTask().execute();                        //下拉功能演示完之后,这个地方是跳到GridView界面去                        Intent intent = new Intent(GridActivity.this, WebViewActivity.class);                        startActivity(intent);                    }                });

webview.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:ptr="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context=".MainActivity">    <com.handmark.pulltorefresh.library.PullToRefreshWebView        android:id="@+id/pull_refresh_webview"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        ptr:ptrMode="both"        >    </com.handmark.pulltorefresh.library.PullToRefreshWebView></RelativeLayout>

WebViewActivity.java文件

package com.example.chenyu.pulltorefresh;import android.content.Intent;import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.handmark.pulltorefresh.library.ILoadingLayout;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshListView;import com.handmark.pulltorefresh.library.PullToRefreshWebView;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class WebViewActivity extends AppCompatActivity {    private PullToRefreshWebView pullToRefreshWebView;    private WebView webView;    List<Map<String,Object>> mData=new ArrayList<Map<String,Object>>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.webview);        pullToRefreshWebView= (PullToRefreshWebView) findViewById(R.id.pull_refresh_webview);        webView= pullToRefreshWebView.getRefreshableView();        webView.loadUrl("http://www.baidu.com");        //设置WebView属性,能够执行Javascript脚本        webView.getSettings().setJavaScriptEnabled(true);        webView.setWebViewClient(new WebViewClient() {            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                      webView.loadUrl(url);                return false;            }        });//        lv= (PullToRefreshListView)findViewById(R.id.pull_refresh_list);//        mData=getmData();//        adapter=new SimpleAdapter(this,mData,R.layout.simple_list_item_2,new String[]{"title","text"},new int[]{R.id.text1,R.id.text2});//        lv.setAdapter(adapter);        initIndicator();       // 刷新监听事件        pullToRefreshWebView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<WebView>() {            @Override            public void onRefresh(PullToRefreshBase<WebView> refreshView) {                // 模拟加载任务                new GetDataTask().execute();                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                String label = simpleDateFormat.format(System.currentTimeMillis());                // 显示最后更新的时间                refreshView.getLoadingLayoutProxy()                        .setLastUpdatedLabel(label);            }        });//      //  下拉刷新 上拉加载//        pullToRefreshWebView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {//            @Override//            public void onPullDownToRefresh(PullToRefreshBase refreshView) {//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//                String label = simpleDateFormat.format(System.currentTimeMillis());//                Toast.makeText(WebViewActivity.this, "PullDownRefresh", Toast.LENGTH_SHORT).show();//                new GetDataTask().execute();////                // 显示最后更新的时间//                refreshView.getLoadingLayoutProxy()//                        .setLastUpdatedLabel(label);//            }////            @Override//            public void onPullUpToRefresh(PullToRefreshBase refreshView) {//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//                String label = simpleDateFormat.format(System.currentTimeMillis());//                Toast.makeText(WebViewActivity.this, "PullUpToRefresh", Toast.LENGTH_SHORT).show();////                Intent intent = new Intent(MainActivity.this, GridActivity.class);////                startActivity(intent);////                new GetDataTask().execute();////                // 显示最后更新的时间////                refreshView.getLoadingLayoutProxy()////                        .setLastUpdatedLabel(label);//            }////        });    }    @Override    //设置回退    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法    public boolean onKeyDown(int keyCode, KeyEvent event) {        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {            webView.goBack(); //goBack()表示返回WebView的上一页面            return true;        }        return false;    }    private void initIndicator()    {        ILoadingLayout startLabels = pullToRefreshWebView                .getLoadingLayoutProxy(true, false);        startLabels.setPullLabel("就把我往死里面拉吧...");// 刚下拉时,显示的提示        startLabels.setRefreshingLabel("正在刷新...");// 刷新时        startLabels.setReleaseLabel("放了我,我就刷新...");// 下来达到一定距离时,显示的提示        ILoadingLayout endLabels = pullToRefreshWebView.getLoadingLayoutProxy(                false, true);        endLabels.setPullLabel("就把我往死里面拉吧123...");// 刚下拉时,显示的提示        endLabels.setRefreshingLabel("正在刷新123...");// 刷新时        endLabels.setReleaseLabel("放了我,我就刷新123...");// 下来达到一定距离时,显示的提示    }    private class GetDataTask extends AsyncTask<Void, Void, Void>    {        @Override        protected Void doInBackground(Void... params) {            Map<String,Object> map=new HashMap<String,Object>();            //如果这个地方不使用线程休息的话,刷新就不会显示在那个PullToRefreshListView的UpdatedLabel上面            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }            return null;        }        @Override        protected void onPostExecute(Void aVoid) {            super.onPostExecute(aVoid);            webView.getSettings().setBuiltInZoomControls(true);            webView.getSettings().setSupportZoom(true);            //加载需要显示的网页            webView.loadUrl("http://www.baidu.com");            pullToRefreshWebView.onRefreshComplete();        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

效果图如下



关键函数

webView= pullToRefreshWebView.getRefreshableView();
锁定客户端,不要点击跳到安卓内置浏览器里面去了
webView.setWebViewClient(new WebViewClient() {            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {                      webView.loadUrl(url);                return false;            }        });
可以按回退键返回
 @Override    //设置回退    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法    public boolean onKeyDown(int keyCode, KeyEvent event) {        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {            webView.goBack(); //goBack()表示返回WebView的上一页面            return true;        }        return false;    }
还要记得加上权限

在AndroidManifest.xml里面加上

<uses-permission android:name="android.permission.INTERNET" />

好了,结束了,要是有什么不懂的加我QQ:2657607916









更多相关文章

  1. 一个Activity的显示过程总结(二)
  2. Android中关于退出和Toast的引用
  3. Android(安卓)自定义弹窗 Dialog
  4. Android(安卓)ActionBar详解
  5. android service中显示一个dialog
  6. android:ListView下拉刷新上拉加载更多(PullToRefresh框架抽取)
  7. Android(安卓)系统第三方应用系统修改权限及在应用上层显示权限
  8. [已解决]Android(安卓)ListView EditView 获取焦点问题
  9. osg for android 学习之十五:显示图片

随机推荐

  1. Android(安卓)HAL开发
  2. 安卓开发学习笔记
  3. 【Android】Android和PHP开发最佳实践完
  4. android的edittext怎么设置不默认被选中,
  5. 为Android内核添加新驱动,并添加到menucon
  6. Android之Animation
  7. android ndk 使用第三方静态库
  8. No IDEA annotations attached to the JD
  9. android中Message机制的灵活应用
  10. android开发积累4-android使用HttpURLCon