多条目加载

<?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"
    tools:context="com.example.wz.yuekaodemo.MainActivity">

    <me.maxwin.view.XListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>
<?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">
    <LinearLayout android:layout_width="0dp"
                  android:layout_weight="1"
                  android:layout_height="match_parent"
                  android:orientation="vertical"
                  android:paddingLeft="5dp"
                  android:paddingRight="5dp"
                  android:paddingTop="3dp"
                  android:paddingBottom="3dp">
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:textSize="16sp"
            android:textStyle="bold"
            android:textColor="#3c4c5d"
            android:layout_height="60dp"/>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/site"
                android:textSize="14sp"
                android:textColor="#c3c3c3"
                android:layout_alignParentLeft="true"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"/>
            <TextView
                android:id="@+id/time"
                android:textSize="14sp"
                android:textColor="#c3c3c3"
                android:layout_alignParentRight="true"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"/>
        </RelativeLayout>

    </LinearLayout>

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="fitXY"/>


</LinearLayout>
<?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">
    <LinearLayout android:layout_width="0dp"
                  android:layout_weight="1"
                  android:layout_height="match_parent"
                  android:orientation="vertical"
                  android:paddingLeft="5dp"
                  android:paddingRight="5dp"
                  android:paddingTop="3dp"
                  android:paddingBottom="3dp">
        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:textSize="16sp"
            android:textStyle="bold"
            android:textColor="#3c4c5d"
            android:layout_height="60dp"/>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/site"
                android:textSize="14sp"
                android:textColor="#c3c3c3"
                android:layout_alignParentLeft="true"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"/>
            <TextView
                android:id="@+id/time"
                android:textSize="14sp"
                android:textColor="#c3c3c3"
                android:layout_alignParentRight="true"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"/>
        </RelativeLayout>

    </LinearLayout>

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="fitXY"/>


</LinearLayout>
public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener{
    private XListView lv;
    private List<Data.DataBean.ArticleListBean> list;
    private MyAdapter adapter;
    private String urlPath = "http://zkread.com/htnewsroom/v2.0/mobileapp/user-0/categories/articles?itemType=recommendation&itemName=%25E6%258E%25A8%25E8%258D%2590&itemId=-1&size=20&firstId=1338557&page=1";
    private int page = 1;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Gson gson=new Gson();
            Data data= gson.fromJson(msg.obj.toString(),Data.class);
            list.addAll(data.getData().getArticleList());
            adapter.notifyDataSetChanged();

            stopXList();
        }
    };

    private void stopXList() {
        lv.stopRefresh();
        lv.stopLoadMore();
        lv.setRefreshTime("刚刚");
    }

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

        initView();
        loadData();
    }

    @Override
    public void onRefresh() {
        page=1;
        list.clear();
        loadData();
    }

    @Override
    public void onLoadMore() {
        page++;
        loadData();
    }

    private void loadData() {


                String result = UrlUtils.getUrlConnect(urlPath+page);
                Message msg=Message.obtain();
                msg.what=1;
                msg.obj=result;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    private void initView() {
        lv= (XListView) findViewById(R.id.lv);
        lv.setPullLoadEnable(true);
        lv.setXListViewListener(this);
        list=new ArrayList<>();
        adapter=new MyAdapter(this,list);
        adapter =new MyAdapter (adapter);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if(position>0&&position<list.size()){
                    Data.DataBean.ArticleListBean bean = list.get(position-1);
                    Toast.makeText(MainActivity.this, bean.getTitle(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
public class MyAdapter extends BaseAdapter{
    private Context context;
    private List<Data.DataBean.ArticleListBean> list;
    ImageLoader imageloader;
    DisplayImageOptions options;

    private final int TYPE0 = 0;
    private final int TYPE1 = 1;

    public MyAdapter(Context context, List<Data.DataBean.ArticleListBean> list) {
        this.context = context;
        this.list = list;

        //创建默认的ImageLoader配置参数
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration
                .createDefault(context);

        //将configuration配置到imageloader中
        imageloader=ImageLoader.getInstance();
        imageloader.init(configuration);

        options=new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .build();
    }

    @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 int getItemViewType(int position) {
//        Log.e("getItemViewType", "getItemViewType: "+position);
//        switch (position){
//            case TYPE0:
//                return TYPE0;
//            case TYPE1:
//                return TYPE1;
//            default:
//                return TYPE1;
//        }
        return list.get(position).getImgSrc().startsWith("http")?TYPE1:TYPE0;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        Log.e("getView", "getView: "+position);
        int type = getItemViewType(position);
        if(convertView==null){
            holder=new ViewHolder();

            if(type==TYPE0){
                convertView=View.inflate(context,R.layout.item0,null);
            }else if(type==TYPE1){
                convertView=View.inflate(context,R.layout.item,null);
                holder.image = (ImageView)convertView.findViewById(R.id.image);
            }

            holder.title= (TextView) convertView.findViewById(R.id.title);
            holder.site= (TextView) convertView.findViewById(R.id.site);
            holder.time= (TextView) convertView.findViewById(R.id.time);

            convertView.setTag(holder);
        }else{
            holder= (ViewHolder) convertView.getTag();
        }

        Data.DataBean.ArticleListBean bean = list.get(position);
        holder.title.setText(bean.getTitle());
        holder.site.setText(bean.getSite());
        holder.time.setText(longData2Str(bean.getCreateTime()));


        if(type==TYPE1){
            imageloader.displayImage(bean.getImgSrc(),holder.image,options);
        }

        return convertView;
    }

    class ViewHolder{
        TextView title,site,time;
        ImageView image;
    }


    public  String longData2Str(long time){
        Date date=new Date(time);
        SimpleDateFormat format=new SimpleDateFormat("HH:mm");
        return  format.format(date);
    }
}
public class UrlUtils {
    /**
         * HttpURLConnection的post请求
         * @param urlPath
         * @param map
         * @return
         */
        public static String postUrlConnect(String urlPath, Map<String,Object> map){
           StringBuffer sbRequest =new StringBuffer();
            if(map!=null&&map.size()>0){
                for (String key:map.keySet()){
                    sbRequest.append(key+"="+map.get(key)+"&");
                }
            }
            String request = sbRequest.substring(0,sbRequest.length()-1);
            try {
                //创建URL
                URL url = new URL(urlPath);
                //由URL的openConnection方法得到一个HttpURLConnection(需要强转)
                HttpURLConnection httpURLConnection =
                        (HttpURLConnection) url.openConnection();
                //设置post提交
                httpURLConnection.setRequestMethod("POST");
                //设置超时时间
                httpURLConnection.setConnectTimeout(30000);
                httpURLConnection.setReadTimeout(30000);

                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);

                //把请求正文通过OutputStream发出去
                OutputStream os =httpURLConnection.getOutputStream();
                os.write(request.getBytes());
                os.flush();

                //判断响应码  200 代表成功
                if(httpURLConnection.getResponseCode()==200){
                    //由HttpURLConnection拿到输入流
                    InputStream in=httpURLConnection.getInputStream();
                    StringBuffer sb=new StringBuffer();
                    //根据输入流做一些IO操作
                    byte [] buff =new byte[1024];
                    int len=-1;
                    while((len=in.read(buff))!=-1){
                        sb.append(new String(buff,0,len,"utf-8"));
                    }

                    in.close();
                    os.close();
                    httpURLConnection.disconnect();
                    return  sb.toString();
                }else{
                    return null;
                }

            }catch (Exception e){
                Log.e("post","code:"+e.getMessage());
                return null;
            }
        }

        /**
         * HttpURLConnection的get请求
         * @param urlPath
         * @return
         */
        public static String getUrlConnect(String urlPath){

            try {
                //创建URL
                URL url = new URL(urlPath);
                //由URL的openConnection方法得到一个HttpURLConnection(需要强转)
                HttpURLConnection httpURLConnection =
                        (HttpURLConnection) url.openConnection();
                //设置连接
                httpURLConnection.connect();
                //判断响应码  200 代表成功
                if(httpURLConnection.getResponseCode()==200){
                    //由HttpURLConnection拿到输入流
                    InputStream in=httpURLConnection.getInputStream();
                    StringBuffer sb=new StringBuffer();
                    //根据输入流做一些IO操作
                    byte [] buff =new byte[1024];
                    int len=-1;
                    while((len=in.read(buff))!=-1){
                        sb.append(new String(buff,0,len,"utf-8"));
                    }
                    in.close();
                    httpURLConnection.disconnect();
                    return  sb.toString();
                }else{
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值