xlistview--狸菇涼_

上拉刷新,下拉加載

本文章上拉加載一條數據,下拉加載10條數據,且有兩個方法,,方法1和方法2的有幾個類是一樣的,所以下面就不寫了

1.先找着xlistview的app,把它導裏面:new -->import module-->找到xlistview的app

2.改build.gradle的buildToolsVersion的值改成下面需要的

3.再改build.gradle中的apply plugin的application改成library,,在把applicationId刪掉


封裝類

Utilsstreamtools

/**

 * 流轉化工具類

 */

public class StreamTools {

 

    /**

     * 流轉化成字符串

     * @param is

     * @return

     */

    public static String readFromNetWork(InputStream is){

 

        try {

 

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

 

            byte[] buffer = new byte[1024];

            int len = 0;

            while ((len = is.read(buffer)) != -1){

                baos.write(buffer,0,len);

            }

 

            return baos.toString();

        } catch (IOException e) {

            e.printStackTrace();

        }

 

        return null;

    }

}


Adaptermybaseadapter

public class MyBaseAdapter extends BaseAdapter {

 

    private Context context;

    //private MenuInfo menuInfo;

    private List<MenuInfo.ResultBean.DataBean> list;

    public MyBaseAdapter(Context context, List<MenuInfo.ResultBean.DataBean> list){

            this.context = context;

            //this.menuInfo = menuInfo;

            this.list = list;

    }

 

    /**

     * 加載更多數據

     */

    public void addMore(List<MenuInfo.ResultBean.DataBean> lists,boolean isRefresh){

 

        for (MenuInfo.ResultBean.DataBean data: lists) {

            //將最新的數據添加到適配所定義的集合中

 

            if(isRefresh) {

                //isRefresh true 下拉的動作  要把數據添加到最前面

                list.add(0, data);

            }else {

                //isRefresh false 上拉的動作  要把數據添加到最後面

                list.add(data);

            }

 

        }

 

    }

 

 

    @Override

    public int getCount() {

       /* return menuInfo.getResult().getData() != null ?

                menuInfo.getResult().getData().size() : 0;*/

       return list != null ? list.size() : 0;

    }

 

    @Override

    public Object getItem(int position) {

        return null;

    }

 

    @Override

    public long getItemId(int position) {

        return 0;

    }

 

    @Override

    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;

        if(convertView ==  null){

 

            viewHolder = new ViewHolder();

            convertView = convertView.inflate(context, R.layout.item,null);

            viewHolder.tvDesc = (TextView) convertView.findViewById(R.id.tvDes);

            convertView.setTag(viewHolder);

        }else{

            viewHolder = (ViewHolder) convertView.getTag();

        }

        //設置文本信息

        viewHolder.tvDesc.setText(list.get(position).getTags());

 

 

        return convertView;

    }

 

    //定義V

    static class ViewHolder{

        TextView tvDesc;

 

    }

 

 

 

}

Beanmenuinfo類 這個就不寫了,自己寫吧

Mainactivity

public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {

 

    private static final String TAG = "MainActivity";

    private XListView xLv;

    private int pageIndex = 1;

    private MyBaseAdapter adapter;

    //設置一個標識,判斷用戶是否是上拉還是下拉

    private boolean isRefreash = true;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        xLv = (XListView) findViewById(R.id.xLv);

        //設置是否可以上拉加載更多

        xLv.setPullLoadEnable(true);

        //設置是否可以下拉刷新

        //xLv.setPullRefreshEnable(true);

        xLv.setRefreshTime("10:53:13");

        xLv.setXListViewListener(this);

 

        try {

            getMenuInfo("http://apis.juhe.cn/cook/query.php?" +

                    "key=a7a42220c5c1c5268be7ba25af764f6c&menu="+

                    URLEncoder.encode("祕製紅燒肉","utf-8")+"&pn"+pageIndex+"&rn="+10);

        } catch (Exception e) {

            e.printStackTrace();

        }

 

    }

 

    /**

     * 分頁加載菜譜數據

     */

    private void getMenuInfo(String path){

 

 

 

        new AsyncTask<String,Void,String>(){

 

 

            @Override

            protected void onPostExecute(String s) {

                super.onPostExecute(s);

                //主線程執行

                if(s == null){

                    return;

                }

 

                //解析

                Gson gson = new Gson();

                MenuInfo menuInfo = gson.fromJson(s, MenuInfo.class);

                //UI更改

 

                if(adapter == null) {

                    //如果是adapter第一次進來空 判定爲第一次的默認加載

                    adapter = new MyBaseAdapter(MainActivity.this,

                            menuInfo.getResult().getData());

                }else {

                    //加載更多

                    adapter.addMore(menuInfo.getResult().getData(),isRefreash);

                    adapter.notifyDataSetChanged();

                }

                xLv.setAdapter(adapter);

 

 

            }

 

            @Override

            protected String doInBackground(String... params) {

                //執行網絡請求

 

                try {

                    String path = params[0];

                    URL url = new URL(path);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("GET");

                    connection.setConnectTimeout(5000);

 

                    int code = connection.getResponseCode();

                    if(code == HttpURLConnection.HTTP_OK){

                        //獲取數據

                        InputStream is = connection.getInputStream();

                        String json = StreamTools.readFromNetWork(is);

 

                        return json;

 

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }

 

                return null;

            }

        }.execute(path);

 

 

    }

 

    /**

     * 下拉刷新的時候會執行的方法

     */

    @Override

    public void onRefresh() {

 

        Log.d(TAG, "onRefresh: 下拉");

        //請求第二頁數據,需求:把最新的數據加載最前面

        try {

            isRefreash = true;

            ++pageIndex;//更改請求第幾頁

            getMenuInfo("http://apis.juhe.cn/cook/query.php?" +

                    "key=a7a42220c5c1c5268be7ba25af764f6c&menu="+

                    URLEncoder.encode("祕製紅燒肉","utf-8")+"&pn"+pageIndex+"&rn="+10);

            //停止刷新 , 讓刷新的UI回彈

            xLv.stopRefresh(true);

 

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

 

    }

 

    /**

     * 上拉加載更多數據時所執行的方法

     */

    @Override

    public void onLoadMore() {

 

        Log.d(TAG, "onLoadMore: 上拉");

        try {

            isRefreash = false;

            ++pageIndex;//更改請求第幾頁

            getMenuInfo("http://apis.juhe.cn/cook/query.php?" +

                    "key=a7a42220c5c1c5268be7ba25af764f6c&menu="+

                    URLEncoder.encode("祕製紅燒肉","utf-8")+"&pn"+pageIndex+"&rn="+10);

            xLv.stopLoadMore();

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

 

    }

}



另一種方法的mainactivity類

package com.main.pull_up_refresh;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.gson.Gson;
import com.limxing.xlistview.view.XListView;
import com.main.bean.Bean;
import com.main.myadapter.MyAdapter;
import com.main.utils.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;


public class MainActivityextendsAppCompatActivityimplementsXListView.IXListViewListener {

    privateXListViewxlv;
    private List<Bean.ResultBean.DataBean>data;
    private MyAdaptermyAdapter;
    private boolean up=false;

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

        xlv= (XListView) findViewById(R.id.xlv);
        //是否可以設置上拉加載更多
        xlv.setPullLoadEnable(true);
        //設置是否可以下拉刷新
        xlv.setPullRefreshEnable(true);


        xlv.setRefreshTime("下拉刷新");

        xlv.setXListViewListener(this);

        //固定了  菜名是紅燒肉
        getmenu("http://apis.juhe.cn/cook/query.php?menu=%E7%BA%A2%E7%83%A7%E8%82%89"+
                "&dtype=&pn=0&rn=10&albums=&=&key=d119d136e1a4cc90d44c439a09e0f5a0");

    }

    //加載菜譜數據
    public voidgetmenu(String url) {

        newAsyncTask<String,Void,String>() {


            @Override
            protected voidonPostExecute(String s) {
                super.onPostExecute(s);

                if (s ==null) {
                    return;
                }else{

                    Gson gson =newGson();
                    Bean bean = gson.fromJson(s,Bean.class);
                    data= bean.getResult().getData();
                    myAdapter=newMyAdapter(MainActivity.this,data);
                    xlv.setAdapter(myAdapter);

                }


            }

            @Override
            protectedStringdoInBackground(String... params) {
                try{

                    String param = params[0];

                    URL url1 =newURL(param);

                    HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();

                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(8000);
                    urlConnection.setReadTimeout(8000);

                    if (urlConnection.getResponseCode() ==200) {

                        InputStream inputStream = urlConnection.getInputStream();
                        String geturl = Utils.geturl(inputStream);

                        return geturl;

                    }

                } catch(MalformedURLException e) {
                    e.printStackTrace();
                }catch(IOException e) {
                    e.printStackTrace();
                }


                return null;
            }
        }.execute(url);


    }


    private voidflush(final booleanup,String path) {

        newAsyncTask<String,Void,String>() {

            @Override
            protected voidonPostExecute(String s) {
                super.onPostExecute(s);

                if (s ==null) {
                    return;
                }else{

                    Gson gson =newGson();
                    Bean bean = gson.fromJson(s,Bean.class);
                    List<Bean.ResultBean.DataBean> data1 = bean.getResult().getData();

                    if (up) {
                        MainActivity.this.data.add(0,data1.get(0));
                    }else{
                        for(inti =0;i < data1.size();i++) {

                            data.add(data1.get(i));
                        }
                    }

                    myAdapter.notifyDataSetChanged();

                }

            }

            @Override
            protectedStringdoInBackground(String... params) {
                try{

                    String param = params[0];


                    URL url1 =newURL(param);

                    HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();

                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(8000);
                    urlConnection.setReadTimeout(8000);

                    if (urlConnection.getResponseCode() ==200) {

                        InputStream inputStream = urlConnection.getInputStream();
                        String geturl = Utils.geturl(inputStream);

                        return geturl;

                    }

                } catch(MalformedURLException e) {
                    e.printStackTrace();
                }catch(IOException e) {
                    e.printStackTrace();
                }


                return null;
            }
        }.execute(path);


    }



    //實現接口後自動重寫的     下拉刷新時會執行的方法
    @Override
    public voidonRefresh() {

        Toast.makeText(this,"onRefresh",Toast.LENGTH_SHORT).show();

        int pnn = (data.size() +1);
        up=true;

        flush(up,"http://apis.juhe.cn/cook/query.php?menu=%E7%BA%A2%E7%83%A7%E8%82%89&dtype=&pn="+ pnn
                + "&rn=1&albums=&=&key=d119d136e1a4cc90d44c439a09e0f5a0");

        xlv.stopRefresh(true);

    }

    //實現接口後自動重寫的   上拉加載時會執行的方法
    @Override
    public voidonLoadMore() {

        Toast.makeText(this,"onLoadMore",Toast.LENGTH_SHORT).show();

        up=false;

        int pnn = (data.size() +1);

        flush(up,"http://apis.juhe.cn/cook/query.php?menu=%E7%BA%A2%E7%83%A7%E8%82%89&dtype=&pn="+ pnn
                + "&rn=10&albums=&=&key=d119d136e1a4cc90d44c439a09e0f5a0");

        xlv.stopLoadMore("onLoadMoreccc");

    }


}


Mybaseadapter

package com.main.myadapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.main.bean.Bean;
import com.main.pull_up_refresh.R;

import java.util.List;

/**
 *時間:2017/4/29
 * 類用途:
 */

public class MyAdapterextendsBaseAdapter {


    privateContextcontext;
    private List<Bean.ResultBean.DataBean>list;

    public MyAdapter(Context context,List<Bean.ResultBean.DataBean> list) {
        this.context= context;
        this.list= list;
    }


    @Override
    public intgetCount() {
        returnlist!=null?list.size() :0;
    }

    @Override
    publicObjectgetItem(intposition) {
        returnlist.get(position);
    }

    @Override
    public longgetItemId(intposition) {
        returnposition;
    }

    @Override
    publicViewgetView(intposition,View convertView,ViewGroup parent) {

        if(convertView ==null){

            convertView = View.inflate(context,R.layout.item,null);

        }

        TextView textView = (TextView) convertView.findViewById(R.id.text_item);

        textView.setText(list.get(position).getId()+"     "+list.get(position).getTags());

        return convertView;
    }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章