多条目的XListView

MainActivity

 private XListView contents;
    private ContentsAdapter mAdapter;

private int mPage;
private final int LOAD_COUNT = 10;

@Override

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

    mPage = 1;

    contents = findViewById(R.id.contents);
    mAdapter = new ContentsAdapter(this);
    contents.setAdapter(mAdapter);
    contents.setPullRefreshEnable(true);
    contents.setPullLoadEnable(true);

    contents.setXListViewListener(new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            mPage = 1;
            loadData();
        }

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

    loadData();
}

private void loadData() {
    if(mPage == 1) {
        loadBannerData();

        loadNesData();
    } else {
        loadNesData();
    }
}

private void loadBannerData() {
    NetUtils.getInstance().getRequest(bannerUrl, BannerResponse.class, new NetUtils.Callback<BannerResponse>() {
        @Override
        public void onSuccess(BannerResponse o) {
            mAdapter.setBanner(o.getData());
        }
    });
}

private void loadNesData() {
    NetUtils.getInstance().getRequest(String.format(newsUrl, LOAD_COUNT, mPage), NewsResponse.class, new NetUtils.Callback<NewsResponse>() {
        @Override
        public void onSuccess(NewsResponse o) {
            if(mPage == 1) {
                mAdapter.setDatas(o.getResult());
            } else {
                mAdapter.addDatas(o.getResult());
            }

            //停止刷新加载
            contents.stopRefresh();
            contents.stopLoadMore();
            if(o.getResult().size() < LOAD_COUNT) {
                contents.setPullLoadEnable(false);
            }
        }
    });
}

//banner url
private String bannerUrl = "http://www.zhaoapi.cn/quarter/getAd";
//news url
private String newsUrl = "http://172.17.8.100/movieApi/movie/v1/findHotMovieList?count=%d&page=%d";

Adapter
ConntentAdapter
//banner数据
private List<BannerResponse.DataBean> mBanner;
private List<NewsResponse.ResultBean> mDatas;
private Context mContext;

public ContentsAdapter(Context context) {
    this.mContext = context;
    mBanner = new ArrayList<>();
    mDatas = new ArrayList<>();
}

//更新banner
public void setBanner(List<BannerResponse.DataBean> banner) {
    mBanner.clear();
    if (banner != null) {
        mBanner.addAll(banner);
    }
    notifyDataSetChanged();
}

//更新新闻数据
public void setDatas(List<NewsResponse.ResultBean> datas) {
    mDatas.clear();
    if(datas != null) {
        mDatas.addAll(datas);
    }
    notifyDataSetChanged();
}

//追加新闻数据
public void addDatas(List<NewsResponse.ResultBean> datas) {
    if(datas != null) {
        mDatas.addAll(datas);
    }
    notifyDataSetChanged();
}

@Override
public int getCount() {
    //return mDatas.size() + 1;
    return hasBanner() ? mDatas.size() + 1 : mDatas.size();
}

//是否有banner
private boolean hasBanner() {
    return mBanner.size() > 0;
}

@Override
public NewsResponse.ResultBean getItem(int position) {
    return mDatas.get(hasBanner() ? position - 1 : position);
}

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

private final int ITEM_COUNT = 2;
private final int BANNER_TYPE = 0;
private final int NEWS_TYPE = 1;

@Override
public int getViewTypeCount() {
    //banner + news
    return ITEM_COUNT;
}

@Override
public int getItemViewType(int position) {
    //return super.getItemViewType(position);
    return position == 0 && hasBanner() ? BANNER_TYPE : NEWS_TYPE;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (getItemViewType(position) == BANNER_TYPE) {
        BannerViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_banner, parent, false);
            viewHolder = new BannerViewHolder(convertView);
        } else {
            viewHolder = (BannerViewHolder) convertView.getTag();
        }
        viewHolder.bindData(mContext, mBanner);
    } else {
        NewsViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_news, parent, false);
            viewHolder = new NewsViewHolder(convertView);
        } else {
            viewHolder = (NewsViewHolder) convertView.getTag();
        }
        viewHolder.bindData(getItem(position));
    }

    return convertView;
}

class BannerViewHolder {
    ViewPager viewPager;

    private android.os.Handler mHandler = new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            mHandler.sendEmptyMessageDelayed(0, 2000);
        }
    };

    public BannerViewHolder(View itemView) {
        viewPager = itemView.findViewById(R.id.banner);
        itemView.setTag(this);
    }


    public void bindData(Context context, List<BannerResponse.DataBean> datas) {
        //先取消掉切换任务
        mHandler.removeCallbacksAndMessages(null);
        viewPager.setAdapter(new BannerPagerAdapter(datas, context));
        //2147483648     10000000
        //让ViewPager位于中间
        //左右都伪无限轮播
        //             Banner  LooperViewPager
        //     4 + 2
        //   0   1 2 3 4  0
        viewPager.setCurrentItem(viewPager.getAdapter().getCount() / 2);

        //开始轮播
        mHandler.sendEmptyMessageDelayed(0, 2000);
    }
}

class NewsViewHolder {
    ImageView icon;
    TextView title;
    TextView date;

    public NewsViewHolder(View itemView) {
        icon = itemView.findViewById(R.id.icon);
        title = itemView.findViewById(R.id.title);
        date = itemView.findViewById(R.id.date);
        itemView.setTag(this);
    }

    public void bindData(NewsResponse.ResultBean data) {
        title.setText(data.getName());
        date.setText(data.getSummary());
        ImageLoader.getInstance().displayImage(data.getImageUrl(), icon);
    }
}

BannerAdapter

private List<BannerResponse.DataBean> mDatas;
    private Context context;

public BannerPagerAdapter(List<BannerResponse.DataBean> mDatas, Context context) {
    this.mDatas = mDatas;
    this.context = context;
}

@Override
public int getCount() {
    //TODO 无限
    //return mDatas.size();
    //return Integer.MAX_VALUE;
    return 5000;
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
    return view == o;
}

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
    ImageView imageView = new ImageView(context);

    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
    container.addView(imageView);

    ImageLoader.getInstance().displayImage(mDatas.get(position % mDatas.size()).getIconNoHttps(), imageView, null, new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
            Log.i("TEST", "start: " + imageUri);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            Log.i("TEST", "failed: " + imageUri);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            Log.i("TEST", "complete: " + imageUri);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            Log.i("TEST", "cancelled: " + imageUri);
        }
    });

    return imageView;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    container.removeView((View) object);
}

Util

private static NetUtils instance;
    private Gson gson;

private NetUtils() {
    gson = new Gson();
}

public static NetUtils getInstance() {
    if(instance == null) {
        instance = new NetUtils();
    }
    return instance;
}

public interface Callback<T> {
    void onSuccess(T t);
}

public void getRequest(final String urlStr, final Class clazz, final Callback callback) {
    new AsyncTask<String, Void, Object>(){
        @Override
        protected Object doInBackground(String... strings) {
            return getRequest(urlStr, clazz);
        }

        @Override
        protected void onPostExecute(Object o) {
            callback.onSuccess(o);
        }
    }.execute(urlStr);
}

//是否有网络
public static boolean hasNetwork(Context context) {
    return true;
}

public <T> T getRequest(String urlStr, Class clazz) {
    return (T) gson.fromJson(getRequest(urlStr), clazz);
}

public String getRequest(String urlStr) {
    String result = "";

    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        //
        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);
        int responseCode = urlConnection.getResponseCode();
        if(responseCode == 200) {
            result = stream2String(urlConnection.getInputStream());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

private String stream2String(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    for (String tmp = br.readLine(); tmp != null ; tmp = br.readLine()) {
        sb.append(tmp);
    }

    return sb.toString();
}

App全局加载

@Override
    public void onCreate() {
        super.onCreate();

    ImageLoader.getInstance().init(
            new ImageLoaderConfiguration.Builder(this)
                    .diskCacheSize(50*1024*1024)
                    .memoryCacheSizePercentage(13)
                    .defaultDisplayImageOptions(
                            new DisplayImageOptions.Builder()
                                    .cacheInMemory(true)
                                    .cacheOnDisk(true)

                                    .bitmapConfig(Bitmap.Config.ARGB_4444)

                                    .showImageOnLoading(R.mipmap.ic_launcher)
                                    .showImageOnFail(R.mipmap.ic_launcher)
                                    .showImageForEmptyUri(R.mipmap.ic_launcher)

                                    .displayer(new RoundedBitmapDisplayer(16))
                                    .build()
                    )
                    .build()
    );
}

JavaBean

 private String message;
    private String status;
    private List<ResultBean> result;

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public List<ResultBean> getResult() {
    return result;
}

public void setResult(List<ResultBean> result) {
    this.result = result;
}

public static class ResultBean {
    private boolean followMovie;
    private int id;
    private String imageUrl;
    private String name;
    private int rank;
    private String summary;

    public boolean isFollowMovie() {
        return followMovie;
    }

    public void setFollowMovie(boolean followMovie) {
        this.followMovie = followMovie;
    }

    public int getId() {
        return id;
    }

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

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRank() {
        return rank;
    }

    public void setRank(int rank) {
        this.rank = rank;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }
}




private String msg;
    private String code;
    private List<DataBean> data;

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

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

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

public static class DataBean {
    private int aid;
    private String createtime;
    private String icon;
    private Object productId;
    private String title;
    private int type;
    private String url;

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public String getCreatetime() {
        return createtime;
    }

    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }

    public String getIcon() {
        return icon;
    }

    public String getIconNoHttps() {
        return icon.replace("https", "http");
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public Object getProductId() {
        return productId;
    }

    public void setProductId(Object productId) {
        this.productId = productId;
    }

    public String getTitle() {
        return title;
    }

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

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

Xml

<me.maxwin.view.XListView
        android:id="@+id/contents"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
<android.support.v4.view.ViewPager
        android:id="@+id/banner"
        android:layout_width="0dp"
        android:layout_height="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/date"
    android:text="text"
    android:maxLines="3"
    app:layout_constraintBottom_toBottomOf="@id/icon"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@id/icon"
    />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值