PullToRefresh练习

案例一:

导入依赖:

implementation project(':library')

item_layout条目布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/pic_iv"
        android:layout_width="100dp"
        android:src="@mipmap/ic_launcher"
        android:layout_height="100dp"
        android:layout_margin="10dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/food_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/str_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:textSize="18sp" />
    </LinearLayout>
</LinearLayout>

自定义类:

public class FoodEntity {
    private String title;
    private String str;
    private int img = R.mipmap.ic_launcher;

    public FoodEntity(String title, String str) {
        this.title = title;
        this.str = str;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }

    @Override
    public String toString() {
        return "FoodEntity{" +
                "title='" + title + '\'' +
                ", str='" + str + '\'' +
                ", img=" + img +
                '}';
    }
}

MainActivity布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mrzhao.exam1demo.MainActivity">

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></com.handmark.pulltorefresh.library.PullToRefreshListView>


</LinearLayout>

MainActivity:

public class MainActivity extends AppCompatActivity {

    private PullToRefreshListView listView;
    private List<FoodEntity>  list = new ArrayList<>();
    private MyAdapter myAdapter;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(MainActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
            //模拟刷新操作
            list.clear();
            initData();
            myAdapter.notifyDataSetChanged();
            //表示刷新完成
            listView.onRefreshComplete();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (PullToRefreshListView) findViewById(R.id.listView);
        //设置模式  支持 下拉刷新 和上拉加载更多
        listView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        initData();
        myAdapter = new MyAdapter(list, this);

        listView.setAdapter(myAdapter);
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    handler.sendEmptyMessageDelayed(100,5000);
            }
        });
    }

    private void initData() {
        for (int i = 0; i < 100; i++) {
            list.add(new FoodEntity("菜名"+i,"用料表"));
        }
    }
}

适配器:

public class MyAdapter extends BaseAdapter {

    private List<FoodEntity>  list ;
    private Context  context;
    private LayoutInflater inflater;

    public MyAdapter(List<FoodEntity> list, Context context) {
        this.list = list;
        this.context = context;
        inflater =  LayoutInflater.from(context);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHodler hodler =  null;
        if (convertView == null){
            convertView = inflater.inflate(R.layout.item_layout,parent,false);
            hodler = new ViewHodler();
            hodler.strTv =  convertView.findViewById(R.id.str_tv);
            hodler.titleTv =  convertView.findViewById(R.id.food_tv);
            convertView.setTag(hodler);
        }else {
            hodler = (ViewHodler) convertView.getTag();
        }
        FoodEntity foodEntity = list.get(position);
        hodler.titleTv .setText(foodEntity.getTitle());
        hodler.strTv.setText(foodEntity.getStr());
        return convertView;
    }
    static class ViewHodler{
        TextView titleTv;
        TextView strTv;
    }
}

案例二:

权限:

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

导入依赖:

compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.picasso:picasso:2.5.2'
implementation project(':library')

item_layout条目布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/food_pic_iv"
        android:layout_width="100dp"
        android:src="@mipmap/ic_launcher"
        android:layout_height="100dp"
        android:layout_margin="10dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/food_title_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/food_str_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:textSize="18sp" />
    </LinearLayout>
</LinearLayout>

解析类:

public class FoodEntity implements Serializable {


    /**
     * ret : 1
     * data : [{"id":"8289","title":"油焖大虾","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg","collect_num":"1660","food_str":"大虾 葱 生姜 植物油 料酒","num":1660},{"id":"2127","title":"四川回锅肉","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg","collect_num":"1586","food_str":"猪肉 青蒜 青椒 红椒 姜片","num":1586},{"id":"30630","title":"超简单芒果布丁","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg","collect_num":"1529","food_str":"QQ糖 牛奶 芒果","num":1529},{"id":"9073","title":"家常红烧鱼","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9073.jpg","collect_num":"1420","food_str":"鲜鱼 姜 葱 蒜 花椒","num":1420},{"id":"10097","title":"家常煎豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10097.jpg","collect_num":"1408","food_str":"豆腐 新鲜红椒 青椒 葱花 油","num":1408},{"id":"10509","title":"水煮肉片","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10509.jpg","collect_num":"1337","food_str":"瘦猪肉 生菜 豆瓣酱 干辣椒 花椒","num":1337},{"id":"46968","title":"红糖苹果银耳汤","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/47/46968.jpg","collect_num":"1245","food_str":"银耳 苹果 红糖","num":1245},{"id":"10191","title":"麻婆豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10191.jpg","collect_num":"1215","food_str":"豆腐 肉末 生抽 白糖 芝麻油","num":1215},{"id":"2372","title":"皮蛋瘦肉粥","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2372.jpg","collect_num":"1147","food_str":"大米 皮蛋 猪肉 油条 香葱","num":1147},{"id":"2166","title":"蚂蚁上树","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2166.jpg","collect_num":"1141","food_str":"红薯粉 肉 姜 蒜 花椒","num":1141},{"id":"2262","title":"糖醋肉","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2262.jpg","collect_num":"1075","food_str":"猪肉 红椒 黄椒 洋葱 蛋清","num":1075},{"id":"9971","title":"鱼香豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9971.jpg","collect_num":"1005","food_str":"豆腐 木耳 胡萝卜 香葱 番茄酱","num":1005},{"id":"10172","title":"干煸四季豆","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10172.jpg","collect_num":"989","food_str":"四季豆 干辣椒 蒜头 酱油 糖","num":989},{"id":"2685","title":"胡萝卜肉末蒸蛋","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2685.jpg","collect_num":"918","food_str":"胡萝卜 肉 蛋 生抽 盐","num":918},{"id":"9972","title":"虎皮青椒","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9972.jpg","collect_num":"890","food_str":"青辣椒 大蒜 香醋 白糖 生抽","num":890},{"id":"10437","title":"叉烧排骨","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10437.jpg","collect_num":"797","food_str":"排骨 李锦记叉烧酱 植物油 清水 油菜","num":797},{"id":"2892","title":"\u201c五行\u201d彩蔬汤","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2892.jpg","collect_num":"757","food_str":"黑木耳 玉米 牛蒡 胡萝卜 西兰花","num":757},{"id":"10044","title":"土豆炖翅根","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10044.jpg","collect_num":"753","food_str":"土豆 翅根 葱 姜 料酒","num":753},{"id":"33783","title":"美人豆浆","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/34/33783.jpg","collect_num":"753","food_str":"黄豆 红豆 绿豆 黑豆 黑米","num":753},{"id":"2348","title":"麻辣肉丝面","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2348.jpg","collect_num":"753","food_str":"面条 肉丝 淀粉 酱油 辣椒","num":753}]
     */

    private int ret;
    private List<DataBean> data;

    public int getRet() {
        return ret;
    }

    public void setRet(int ret) {
        this.ret = ret;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean implements Serializable {
        /**
         * id : 8289
         * title : 油焖大虾
         * pic : http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg
         * collect_num : 1660
         * food_str : 大虾 葱 生姜 植物油 料酒
         * num : 1660
         */

        private String id;
        private String title;
        private String pic;
        private String collect_num;
        private String food_str;
        private int num;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getPic() {
            return pic;
        }

        public void setPic(String pic) {
            this.pic = pic;
        }

        public String getCollect_num() {
            return collect_num;
        }

        public void setCollect_num(String collect_num) {
            this.collect_num = collect_num;
        }

        public String getFood_str() {
            return food_str;
        }

        public void setFood_str(String food_str) {
            this.food_str = food_str;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }
    }
}

MainActivity布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mrzhao.exam2demo.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:text="点击获取网络数据"
        android:onClick="onClick"
        android:layout_height="wrap_content"
        tools:ignore="OnClick" />
</LinearLayout>

MainActivity:

public class MainActivity extends AppCompatActivity {
    private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        new MyTask().execute();
    }

    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            return getDataFromNet(path);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (!TextUtils.isEmpty(s)) {
                Gson gson = new Gson();
                FoodEntity foodEntity = gson.fromJson(s, FoodEntity.class);
                Intent intent = new Intent(MainActivity.this, InfoActivity.class);
                intent.putExtra("info", foodEntity);
                startActivity(intent);

            }
        }
    }

    private String getDataFromNet(String path) {
        InputStream inputStream;
        ByteArrayOutputStream outputStream;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            conn.setReadTimeout(10 * 1000);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                return outputStream.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

InfoActivity布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mrzhao.exam2demo.InfoActivity">


    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></com.handmark.pulltorefresh.library.PullToRefreshListView>

</LinearLayout>

InfoActivity:

public class InfoActivity extends AppCompatActivity {
    private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=";
    private int pager =1;
    private List<FoodEntity.DataBean> list = new ArrayList<>();
    private PullToRefreshListView listview;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        FoodEntity foodEntity = (FoodEntity) getIntent().getSerializableExtra("info");
        List<FoodEntity.DataBean> data = foodEntity.getData();
        list.addAll(data);

        listview = (PullToRefreshListView) findViewById(R.id.listView);
        listview.setMode(PullToRefreshBase.Mode.BOTH);
        myAdapter = new MyAdapter(list, this);
        listview.setAdapter(myAdapter);
        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                list.clear();
                pager=1;
                new MyTask().execute();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pager++;
                new MyTask().execute();
            }
        });
    }



    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            return getDataFromNet(path+pager);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            listview.onRefreshComplete();
            if (!TextUtils.isEmpty(s)) {
                Gson gson = new Gson();
                FoodEntity foodEntity = gson.fromJson(s, FoodEntity.class);
                List<FoodEntity.DataBean> data = foodEntity.getData();
                list.addAll(data);
                myAdapter.notifyDataSetChanged();


            }
        }
    }

    private String getDataFromNet(String path) {
        InputStream inputStream;
        ByteArrayOutputStream outputStream;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            conn.setReadTimeout(10 * 1000);
            conn.connect();
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
                outputStream = new ByteArrayOutputStream();
                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                return outputStream.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

适配器:

public class MyAdapter extends BaseAdapter {

    private List<FoodEntity.DataBean>  list ;
    private Context  context;
    private LayoutInflater inflater;

    public MyAdapter(List<FoodEntity.DataBean> list, Context context) {
        this.list = list;
        this.context = context;
        inflater =  LayoutInflater.from(context);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHodler hodler =  null;
        if (convertView == null){
            convertView = inflater.inflate(R.layout.item_layout,parent,false);
            hodler = new ViewHodler();
            hodler.strTv =  convertView.findViewById(R.id.food_str_tv);
            hodler.titleTv =  convertView.findViewById(R.id.food_title_tv);
            hodler.picIv =  convertView.findViewById(R.id.food_pic_iv);
            convertView.setTag(hodler);
        }else {
            hodler = (ViewHodler) convertView.getTag();
        }

        FoodEntity.DataBean dataBean = list.get(position);

        hodler.titleTv.setText(dataBean.getTitle());
        hodler.strTv.setText(dataBean.getFood_str());
        Picasso.with(context).load(dataBean.getPic()).into(hodler.picIv);

        return convertView;
    }
    static class ViewHodler{
        TextView titleTv;
        TextView strTv;
        ImageView picIv;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值