刷新加载+异步线程



    




package com.example.sunrongzhen1511b20171118;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

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

/**
 * Created by Sun on 2017/11/18.
 */

public class Fragment02 extends Fragment {
    private List list = new ArrayList();
    MyAdapter adapter;
    private View view;
    private PullToRefreshListView mPtListView;
    private String Json_Url = "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/1/";
    int i = 1;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.f2, container, false);
        initView(view);
        adapter = new MyAdapter(getActivity(), list);
        login(Json_Url + i);
        mPtListView.setAdapter(adapter);


        mPtListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshBase refreshView) {
                mPtListView.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        i = 1;
                        list.clear();
                        login(Json_Url + i);
                        mPtListView.onRefreshComplete();


                    }
                }, 1000);
            }
        });
        mPtListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                i++;
                login(Json_Url + i);

            }
        });


        return view;
    }

    private void login(String pamm) {
        new MyTask().execute(pamm);

    }


    private void initView(View view) {
        mPtListView = (PullToRefreshListView) view.findViewById(R.id.ptListView);
    }

    class MyTask extends AsyncTask {

        @Override
        protected String doInBackground(String... params) {
            String jj = params[0];
            NetWorkUtils netWorkUtils = new NetWorkUtils();
            String data = netWorkUtils.getURL(jj);
            return data;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            SuperClass superClass = gson.fromJson(s, SuperClass.class);
            List lists = superClass.getResults();


            list.addAll(lists);

            adapter.notifyDataSetChanged();

        }

    }
}


你可能感兴趣的:(刷新加载+异步线程)