PullToRefresh引入依赖,布局,适配器ListView上拉加载下拉刷新

使用PullToRefreshListView前 先在File-New-import Module 导入pulltoRefreshLibrary,
然后给项目 添加 module的依赖,
选择pulltoRefreshLibrary

activity_main.xml 
<?xml version="1.0" encoding="utf-8"?>
<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:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/refresh_list_view"
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF"
        >
</com.handmark.pulltorefresh.library.PullToRefreshListView>
</RelativeLayout>

适配器里面的
public class MyAdapter extends BaseAdapter{
    List<DBean.NewslistBean> list;
    Context context;
    public MyAdapter(List<DBean.NewslistBean> list, Context context) {
        this.context = context;
        this.list = list;

        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(context);
        ImageLoader.getInstance().init(configuration);
    }

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

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if (view==null){
            view = View.inflate(context,R.layout.list_item,null);

            holder = new ViewHolder();
            holder.imageView = view.findViewById(R.id.list_image);
            holder.textView = view.findViewById(R.id.list_text);

            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }
        holder.textView.setText(list.get(i).getTitle());
        ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(),holder.imageView);
        return view;
    }
    class ViewHolder{
        ImageView imageView;
        TextView textView;
    }
}

MainActivity里面的
import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;import com.google.gson.Gson;import com.handmark.pulltorefresh.library.ILoadingLayout;import com.handmark.pulltorefresh.library.PullToRefreshBase;import com.handmark.pulltorefresh.library.PullToRefreshListView;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.stream.Stream;public class MainActivity extends AppCompatActivity { private List<DBean.NewslistBean> list = new ArrayList<>(); private PullToRefreshListView refreshListView;int num = 1; private MyAdapter myAdapter; private ILoadingLayout endlabels; private ILoadingLayout startlabels; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); refreshListView = (PullToRefreshListView) findViewById(R.id.refresh_list_view); getDataFromNet(); //设置PullToRefreshListView刷新模式,上拉下拉都可以 refreshListView.setMode(PullToRefreshBase.Mode.BOTH); //设置刷新显示的状态,可以下拉,不能上拉 startlabels = refreshListView.getLoadingLayoutProxy(true,false); startlabels.setRefreshingLabel("正在刷新"); startlabels.setPullLabel("下拉刷新"); startlabels.setReleaseLabel("松开刷新"); endlabels = refreshListView.getLoadingLayoutProxy(false,true); endlabels.setRefreshingLabel("正在加载"); endlabels.setPullLabel("上拉加载"); endlabels.setReleaseLabel("松开加载"); //设置监听事件 refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override //下拉刷新调用 public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) { num =1; //获取数据 getDataFromNetxiala(); setAdapter(); } @Override //上拉加载调用 public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) { num++; getDataFromNet(); setAdapter(); } }); } private void setAdapter() { if (myAdapter==null) { myAdapter = new MyAdapter(list, MainActivity.this); refreshListView.setAdapter(myAdapter); }else{ myAdapter.notifyDataSetChanged(); } } private void getDataFromNet() { AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { String path = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page="+num; try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode==200){ InputStream inputStream = connection.getInputStream(); String json = streamtoString(inputStream,"utf-8"); Thread.sleep(2000); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String json) { Gson gson = new Gson(); DBean dBean = gson.fromJson(json, DBean.class); list.addAll(dBean.getNewslist()); long currentTimeMillis = System.currentTimeMillis(); Date date2= new Date(currentTimeMillis); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); String format = dateFormat.format(date2); //设置刷新的时间 endlabels.setLastUpdatedLabel(format); //停止刷新 refreshListView.onRefreshComplete(); setAdapter(); } }; asyncTask.execute(); } private void getDataFromNetxiala() { AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... voids) { String path = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page="+num; try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode==200){ InputStream inputStream = connection.getInputStream(); String json = streamtoString(inputStream,"utf-8"); Thread.sleep(2000); return json; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String json) { Gson gson = new Gson(); DBean dBean = gson.fromJson(json, DBean.class); list.addAll(0,dBean.getNewslist()); long currentTimeMillis = System.currentTimeMillis(); Date date2= new Date(currentTimeMillis); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); String format = dateFormat.format(date2); //设置刷新的时间 startlabels.setLastUpdatedLabel(format); //停止刷新 refreshListView.onRefreshComplete(); setAdapter(); } }; asyncTask.execute(); } private String streamtoString(InputStream inputStream, String charset) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String s= null; StringBuilder builder = new StringBuilder(); while((s=bufferedReader.readLine())!=null){ builder.append(s); } return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return charset; }}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值