ImageLoader,GET,POST获取数据,多条目加载,XListView

来源:互联网 发布:sqlserver视频教程网盘 编辑:程序博客网 时间:2024/06/03 19:09
//主Activity  XListView的view(里有3个java代码)最好放跟MainActivity同级
public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {    //定义的页数    int num = 0;    private List<UserBean.ResultBean.ListBean> list = new ArrayList<>();    private MyAdapter adapter;    private XListView xListView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //xlistview控件        xListView = (XListView) findViewById(R.id.x_list_view);        //设置
//下拉        xListView.setPullRefreshEnable(true);
//上拉        xListView.setPullLoadEnable(true);
//设置了,可以返回上拉和下拉的方法        xListView.setXListViewListener(this);        getPost();    }    //下拉   POST获取数据    private void getPost() {        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {            @Override            protected String doInBackground(Void... voids) {                String path = "http://v.juhe.cn/weixin/query";                try {                    URL url = new URL(path);                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();                    //设置请求                    connection.setRequestMethod("POST");                    connection.setReadTimeout(5000);                    connection.setConnectTimeout(5000);                    //post方式要提交参数给服务器...以流的方式提交给服务器                    connection.setDoOutput(true);                    //设置请求参数的类型                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                    String pathstring = "key=88f7bbc507e3ecacfaeab2b47dd8936f&ps=10&pno=" + num;                    connection.getOutputStream().write(pathstring.getBytes("utf-8"));                    //响应                    int responseCode = connection.getResponseCode();                    if (responseCode == 200) {                        InputStream inputStream = connection.getInputStream();                        String json = StreamToString(inputStream, "utf-8");                        Log.i("json", "json---->" + json);                        return json;                    }                } catch (Exception e) {                    e.printStackTrace();                }                return null;            }    //在这里解析,添加适配器            @Override            protected void onPostExecute(String s) {                super.onPostExecute(s);                //解析                Gson gson = new Gson();                UserBean userBean = gson.fromJson(s, UserBean.class);                list.addAll(0 , userBean.getResult().getList());                //设置适配器                setadapter();                //停止                xListView.stopRefresh();                Date date = new Date(System.currentTimeMillis());                SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");                //设置时间                xListView.setRefreshTime(dateFormat.format(date));            }        };        asyncTask.execute();    }    //设置适配器    private void setadapter() {        if (adapter == null){            adapter = new MyAdapter(MainActivity.this, list);            xListView.setAdapter(adapter);        }else{            adapter.notifyDataSetChanged();        }    }    //解析    private String StreamToString(InputStream inputStream, String s) {        try {            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s);            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);            StringBuilder builder = new StringBuilder();            String string = "";            while ((string = bufferedReader.readLine()) != null){                builder.append(string);            }            bufferedReader.close();            Log.i("builder" , "builder------>" + builder.toString());            return builder.toString();        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    //上拉   GET获取数据
    public void getPostLoadMore() {        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {            @Override            protected String doInBackground(Void... voids) {                String path = "http://v.juhe.cn/weixin/query?key=88f7bbc507e3ecacfaeab2b47dd8936f&ps=10&pno=" + num;                try {                    URL url = new URL(path);                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();                    //设置                      connection.setRequestMethod("GET");                    connection.setReadTimeout(5000);                    connection.setConnectTimeout(5000);                    //获取                    int responseCode = connection.getResponseCode();                    if (responseCode == 200){                        InputStream inputStream = connection.getInputStream();                        String json = StreamToString(inputStream,"utf-8");                        return json;                    }                } catch (Exception e) {                    e.printStackTrace();                }                return "";            }            @Override            protected void onPostExecute(String json) {                Gson gson = new Gson();                UserBean userBean = gson.fromJson(json, UserBean.class);                //dataDataBean.getResults();                //数据要添加到集合的最前边                 list.addAll(userBean.getResult().getList());               setadapter();               //停止刷新                xListView.stopLoadMore();            }        };        asyncTask.execute();    }
    //下拉加载    @Override    public void onRefresh() {        num ++;        Log.i("num" , "下拉num---->" + num);        getPost();//加载到数据之后停止    }    //上拉刷新    @Override    public void onLoadMore() {        if (num > 0){            num --;            getPostLoadMore();        }else{            Toast.makeText(MainActivity.this,"没有最新数据了",Toast.LENGTH_SHORT).show();            xListView.stopLoadMore();        }        Log.i("num" , "上拉num---->" + num);    }
}
//Adapter   listview的适配器
public class MyAdapter extends BaseAdapter {    private static final int IMAGE_ITEM_LEFT = 0;    private static final int IMAGE_ITEM_RIGHT = 1;    Context context;    List<UserBean.ResultBean.ListBean> list;    public MyAdapter(Context context, List<UserBean.ResultBean.ListBean> list) {        this.context = context;        this.list = list;        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));    }    @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;    }    //多条目加载 所需get(1)getViewTypeCount    @Override    public int getViewTypeCount() {        return 2;    }    //多条目加载 所需get(2)getItemViewType    @Override    public int getItemViewType(int position) {        if ((position%2) == 0){            return IMAGE_ITEM_LEFT;        }        return IMAGE_ITEM_RIGHT;    }    @Override    public View getView(int i, View view, ViewGroup viewGroup) {        if (getItemViewType(i) == IMAGE_ITEM_LEFT){            ViewHolderLeft holderLeft;            if (view == null){                holderLeft = new ViewHolderLeft();                view = View.inflate(context , R.layout.image_left , null);                holderLeft.textView = view.findViewById(R.id.text_title);                holderLeft.imageView = view.findViewById(R.id.iamge_01);                view.setTag(holderLeft);            }else{                holderLeft = (ViewHolderLeft) view.getTag();            }            holderLeft.textView.setText(list.get(i).getTitle());            ImageLoader.getInstance().displayImage(list.get(i).getFirstImg() , holderLeft.imageView , getOption());        }else{            ViewHolderRight holderRight;            if (view == null){                holderRight = new ViewHolderRight();                view = View.inflate(context , R.layout.image_right , null);                holderRight.textView = view.findViewById(R.id.text_title);                holderRight.imageView = view.findViewById(R.id.iamge_02);                view.setTag(holderRight);            }else{                holderRight = (ViewHolderRight) view.getTag();            }            holderRight.textView.setText(list.get(i).getTitle());            ImageLoader.getInstance().displayImage(list.get(i).getFirstImg() , holderRight.imageView , getOption());        }        return view;    }    public DisplayImageOptions getOption() {        DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()                .showImageForEmptyUri(R.mipmap.ic_launcher)                .showImageOnFail(R.mipmap.ic_launcher)                .showImageOnLoading(R.mipmap.ic_launcher)                .cacheInMemory(true)                .cacheOnDisk(true)                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)                .resetViewBeforeLoading(true)//在加载之前复位一下显示                .bitmapConfig(Bitmap.Config.RGB_565)//图片的质量                .considerExifParams(true)//是否考虑JPEG图像EXIF参数(旋转,翻转)                .build();        return imageOptions;    }    class ViewHolderLeft{        ImageView imageView;        TextView textView;    }    class ViewHolderRight{        TextView textView;        ImageView imageView;    }}
//XML布局 footer
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content" >    <RelativeLayout        android:id="@+id/xlistview_footer_content"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:padding="10dp" >        <ProgressBar            android:id="@+id/xlistview_footer_progressbar"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:visibility="invisible" />        <TextView            android:id="@+id/xlistview_footer_hint_textview"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:text="@string/xlistview_footer_hint_normal" />    </RelativeLayout></LinearLayout>
//XML布局 header
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:gravity="bottom" >    <RelativeLayout        android:id="@+id/xlistview_header_content"        android:layout_width="fill_parent"        android:layout_height="60dp" >        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:gravity="center"            android:orientation="vertical" android:id="@+id/xlistview_header_text">            <TextView                android:id="@+id/xlistview_header_hint_textview"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/xlistview_header_hint_normal" />            <LinearLayout                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_marginTop="3dp" >                <TextView                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:text="@string/xlistview_header_last_time"                    android:textSize="12sp" />                <TextView                    android:id="@+id/xlistview_header_time"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:textSize="12sp" />            </LinearLayout>        </LinearLayout>        <ImageView            android:id="@+id/xlistview_header_arrow"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignLeft="@id/xlistview_header_text"            android:layout_centerVertical="true"            android:layout_marginLeft="-35dp"            android:src="@drawable/xlistview_arrow" />        <ProgressBar            android:id="@+id/xlistview_header_progressbar"            android:layout_width="30dp"            android:layout_height="30dp"            android:layout_alignLeft="@id/xlistview_header_text"            android:layout_centerVertical="true"            android:layout_marginLeft="-40dp"            android:visibility="invisible" />    </RelativeLayout></LinearLayout>

阅读全文
0 0
原创粉丝点击