1. 程式人生 > >XListView上拉載入下拉重新整理,第一個條目展示Banner輪播圖

XListView上拉載入下拉重新整理,第一個條目展示Banner輪播圖

佈局開始

此處只有xlistview的佈局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="140dp"
        android:layout_height="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="title"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/icon"
        app:layout_constraintTop_toTopOf="@id/icon"
        />

    <TextView
        android:id="@+id/summary"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/icon"
        app:layout_constraintBottom_toBottomOf="@id/icon"
        android:maxLines="2"
        android:text="摘要"
        />

</android.support.constraint.ConstraintLayout>

 

MainActivity

 

package com.xxx.zkb2.activity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.example.mylibrary.me.maxwin.view.XListView;
import com.example.xxx.zkb2.R;
import com.google.gson.Gson;
import com.xxx.zkb2.adapter.NewsAdapter;
import com.xxx.zkb2.model.Banner;
import com.xxx.zkb2.model.News;
import com.xxx.zkb2.utils.HttpUtil;

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

public class MainActivity extends AppCompatActivity {
   /*private  ArrayList<News.ResultBean> newslist;
   private ArrayList<Banner.DataBean> bannerlist;*/
   private XListView xlv;
   private NewsAdapter newsAdapter;
    //每次載入10條
    private int loadItemCount = 2;
    //初始頁面
    private int page=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //查詢資源id
        xlv=findViewById(R.id.xlv);
        //初始化集合
       /* newslist=new ArrayList<News.ResultBean>();
        bannerlist=new ArrayList<Banner.DataBean>();*/
        //新增介面卡(bannerlist是新增在adapter第一條資料中)
        newsAdapter=new NewsAdapter(MainActivity.this);
        xlv.setAdapter(newsAdapter);
        //設定xlistview事件
        xlv.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                page=1;
                //載入輪播圖片
                loadBannerData();
                //載入新聞
                loadNewsData(page);
            }

            @Override
            public void onLoadMore() {

                   loadNewsData(page);
            }
        });
        //一進來預設可以載入更多
        setCanLoadMore(true);
        //一進來就載入:Banner資料和列表資料
        loadBannerData();
        loadNewsData(page);




    }
    //獲得輪播圖片資料
    private void loadBannerData() {
        String path="http://www.zhaoapi.cn/quarter/getAd";
        new AsyncTask<String,Void,List<Banner.DataBean>>(){

            @Override
            protected List<Banner.DataBean> doInBackground(String... strings) {
                String textString=HttpUtil.HttpUrlConnection(strings[0]);
                Banner banner=new Gson().fromJson(textString,Banner.class);
                return banner==null?null:banner.getData();
            }

            @Override
            protected void onPostExecute(List<Banner.DataBean> dataBeans) {
                super.onPostExecute(dataBeans);
               //更新banner資料
                newsAdapter.setbannerData(dataBeans);

            }
        }.execute(path);
    }
  //每次更新追加完資料停止重新整理,停止載入
    private void loadDataCompleted() {

        page++;
        xlv.stopLoadMore();
        xlv.stopRefresh();

    }

    //獲得新聞資料
    @SuppressLint("StaticFieldLeak")
    private void loadNewsData(final int page) {
        Log.e("page", page+"" );
        final String path="http://172.17.8.100/movieApi/movie/v1/findHotMovieList?page="+page+"&count="+loadItemCount;

        new AsyncTask<String,Void,ArrayList<News.ResultBean>>(){

            @Override
            protected ArrayList<News.ResultBean> doInBackground(String... strings) {
                String textString= HttpUtil.HttpUrlConnection(strings[0]);
                Gson gson=new Gson();
                News news=gson.fromJson(textString,News.class);

                return news==null?null: (ArrayList<News.ResultBean>) news.getResult();
            }

            @Override
            protected void onPostExecute(ArrayList<News.ResultBean> resultBeans) {
                super.onPostExecute(resultBeans);
                if(resultBeans==null){
                    Toast.makeText(MainActivity.this,"請求新聞資料失敗",Toast.LENGTH_SHORT).show();
                    return;
                }
                updateData(resultBeans);

                //通知載入資料完成
                loadDataCompleted();

                //是否可以載入更多:載入列表資料不夠loadItemCount則認為沒有下一頁資料
                setCanLoadMore(resultBeans.size()>=loadItemCount);
                //newslist.clear();



            }
        }.execute(path);
    }
    //是否可以載入更多
    private void setCanLoadMore(boolean b) {
        xlv.setPullLoadEnable(b);
    }

    private void updateData(ArrayList<News.ResultBean> resultBeans) {
        if(page==1){
            //更新新聞資料
            newsAdapter.setNewsData(resultBeans);
        } else {
            //追加新聞資料
            newsAdapter.addNewsData(resultBeans);
        }


    }
}

接下來是Adapter類

其中輪播圖介面卡BannerAdapter省略

NewsAdapter,多列表,判斷是否有Banner資料,有的話,集合數量+1。

package com.xxx.zkb2.adapter;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.xxx.zkb2.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xxx.zkb2.activity.MainActivity;
import com.xxx.zkb2.model.Banner;
import com.xxx.zkb2.model.News;

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

public class NewsAdapter extends BaseAdapter{
    private MainActivity mainActivity;
    private ArrayList<News.ResultBean> newslist;
    private ArrayList<Banner.DataBean> bannerlist;
    BannerViewHolder bh;
    public NewsAdapter(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
        newslist=new ArrayList<>();
        bannerlist=new ArrayList<>();
    }
    /**
     * 更新 列表 資料
     * @param
     */
    public void setNewsData(ArrayList<News.ResultBean> resultBeans) {
        newslist.clear();
        newslist.addAll(resultBeans);
        notifyDataSetChanged();
    }
    /**
     * 新增 列表 資料
     * @param
     */
    public void addNewsData(ArrayList<News.ResultBean> resultBeans) {
        newslist.addAll(resultBeans);
        notifyDataSetChanged();
    }

    /**
     * 更新 Banner 資料
     * @param
     */
    public void setbannerData(List<Banner.DataBean> dataBeans) {
        newslist.clear();
        bannerlist.addAll(dataBeans);
        notifyDataSetChanged();
    }
    private boolean hasBanner() {

        return bannerlist.size() > 0;
    }
    @Override
    public int getItemViewType(int position) {
        //有banner 且 position == 0 則是Banner資料
        //0代表banner,1代表新聞列表

        return hasBanner()&&position==0?0:1;
    }

    @Override
    public int getViewTypeCount() {
        return super.getViewTypeCount()+1;
    }

    @Override
    public int getCount() {
        //如果有Banner,則需要展示Banner資料,因此+1
        return newslist.size()+(hasBanner()?1:0);
    }

    @Override
    public Object getItem(int position) {
        if(hasBanner() && position == 0) {
            return null;
        }
        //如果有banner,第一條是Banner資料。因此真正的資料從position -1開始
        return newslist.get(hasBanner()?position-1:position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if(getItemViewType(position)==0){//banner

       if(convertView==null){
           bh = new BannerViewHolder();
           convertView=View.inflate(mainActivity, R.layout.banner,null);
           bh.viewPager=convertView.findViewById(R.id.viewpager);
           convertView.setTag(bh);
       } else {
           bh= (BannerViewHolder) convertView.getTag();
       }
       bh.viewPager.setAdapter(new BannerAdapter(mainActivity,bannerlist));
       //清除之前handler傳送的訊息
       handler.removeCallbacksAndMessages(null);
       //傳送請求
       handler.sendEmptyMessageDelayed(0,2000);
      } else {//news
          ListViewHolder lh = new ListViewHolder();
          if (convertView == null) {
              convertView=View.inflate(mainActivity,R.layout.lv_item,null);
              lh.title = convertView.findViewById(R.id.title);
              lh.summary = convertView.findViewById(R.id.summary);
              lh.icon = convertView.findViewById(R.id.icon);
              convertView.setTag(lh);
          } else {
              lh = (ListViewHolder) convertView.getTag();
          }

         News.ResultBean data= (News.ResultBean) getItem(position);
          lh.title.setText(data.getName());
          lh.summary.setText(data.getSummary());
          ImageLoader.getInstance().displayImage(data.getImageUrl(),lh.icon);
      }
        return convertView;
    }


  Handler handler=new Handler(){
      @Override
      public void handleMessage(Message msg) {
          super.handleMessage(msg);
          switch (msg.what){
              case 0:
                  int positon=bh.viewPager.getCurrentItem();
                  positon++;
                  bh.viewPager.setCurrentItem(positon);
                  handler.sendEmptyMessageDelayed(0,2000);
                  break;
          }
      }
  };
    class BannerViewHolder {
        private ViewPager viewPager;
    }
    class ListViewHolder {
        private ImageView icon;
        private TextView title;
        private TextView summary;
    }
}

輪播圖和新聞的Bean類省略

ImageLoader,載入圖片

package com.xxx.zkb2;

import android.app.Application;
import android.graphics.Bitmap;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoader.getInstance().init(
                new ImageLoaderConfiguration.Builder(this)
                        .memoryCacheSizePercentage(10)
                        .diskCacheSize(50*1024*1024)
                        .defaultDisplayImageOptions(new DisplayImageOptions.Builder()
                                .cacheOnDisk(true)
                                .cacheInMemory(true)
                                .bitmapConfig(Bitmap.Config.ARGB_4444)
                        .build()
                        )
                        .build()
        );

    }
}

效果圖如下