1. 程式人生 > >多條目一,上拉下拉+

多條目一,上拉下拉+

//MainActivity

package com.example.day08_test02;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.day08_test02.Adapter.MyAdapter;
import com.example.day08_test02.Bean.MyimagerBean;
import com.example.day08_test02.Bean.MynewsBean;
import com.example.day08_test02.Utils.Utils;

import java.util.List;

import me.maxwin.view.XListView;

public class MainActivity extends AppCompatActivity {
    private int mPger=1;
    private MyAdapter adapter;
    private XListView xListView;
    private final int LOAD_COUNT = 10;

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

        findViewById(R.id.pager);
        xListView = findViewById(R.id.xlist);
        //設定可擴充套件屬性
        xListView.setPullRefreshEnable(true);
        xListView.setPullLoadEnable(true);

        adapter = new MyAdapter(this);
        xListView.setAdapter(adapter);
        //設定監聽
        xListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                //賦值頁面
                mPger=1;
                loadData();
            }

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

        loadNews();
        loadImage();


    }
    
    //載入資料
    private void loadData() {
        //判斷頁面
        if(mPger==1){
            //載入新聞 載入圖片
            loadImage();
            loadNews();
        }else{
            loadNews();
        }
        
    }
    //新聞的實現方法
    private String urlStr="http://172.17.8.100/movieApi/movie/v1/findHotMovieList?count=%d&page=%d";
    private void loadNews() {
        Utils.getInstance().getRequest03(String.format(urlStr,LOAD_COUNT,mPger),MynewsBean.class, new Utils.CallBack<MynewsBean>() {

            @Override
            public void onSuccess(MynewsBean mynewsBean) {
                //呼叫瞭解析新聞的回撥方法得到回撥值
                List<MynewsBean.Result> result = mynewsBean.getResult();
                //得到新聞的頁面判斷是重新整理還是載入
                if(mPger==1){
                    //重新整理
                    adapter.setDatas(result);
                }else{
                    //載入
                    adapter.addDatas(result);
                }
                //停止
                xListView.stopRefresh();
                xListView.stopLoadMore();
                //判斷
                if(result.size()<LOAD_COUNT){
                    //如果載入之後沒了 就不顯示 上拉載入了
                    xListView.setPullLoadEnable(false);
                }
            }
        });
    }

    //圖片的實現方法
    private String imagerStr="http://www.zhaoapi.cn/quarter/getAd";
    private void loadImage() {
        Utils.getInstance().getRequest03(imagerStr, MyimagerBean.class, new Utils.CallBack<MyimagerBean>() {

            @Override
            public void onSuccess(MyimagerBean myimagerBean) {
                List<MyimagerBean.Data> data = myimagerBean.getData();

                adapter.setImage(data);
            }
        });
    }
}

//App 全域性配置

package com.example.day08_test02;

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;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class App extends Application {
    //一定主義在清單檔案配置
    @Override
    public void onCreate() {
        super.onCreate();
        //開局初始化imageloder
        ImageLoader.getInstance().init(
                //裡面例項化 imageloader全域性配置
                new ImageLoaderConfiguration.Builder(this)
                        //設定緩衝的大小
                .diskCacheSize(50*1024*1024)
                        //設定色彩模式
                .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()
        );
    }
}

//Utils 封裝Async 介面解析

package com.example.day08_test02.Utils;

import android.annotation.SuppressLint;
import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class Utils {
    //定義單例變數
    private  static  Utils instance;
    private Gson gson;
    //構造
    private Utils(){
        gson = new Gson();
    }

    //賦值
    public static Utils getInstance(){
        //判斷
        if(instance==null){
            instance = new Utils();
        }
        return instance;
    }

    //定義介面
    public interface CallBack<T>{
        void onSuccess(T t);
    }

    //定義帶介面的方法
    @SuppressLint("StaticFieldLeak")
    public void  getRequest03(String UrlStr, final Class clazz, final CallBack callBack){
        new AsyncTask<String, Void, Object>() {
            @Override
            protected Object doInBackground(String... strings) {

                return getRequest02(strings[0],clazz);
            }

            @Override
            protected void onPostExecute(Object o) {
                callBack.onSuccess(o);
            }
        }.execute(UrlStr);
    }
    //定義個封裝class的類 掉01,並解析
    public <T> T getRequest02(String UrlStr,Class clazz){
        return (T) gson.fromJson(getRequest01(UrlStr),clazz);
    }
    //定義得到一個string
    public String getRequest01(String urlStr){
        String result = "";
        URL url = null;
        try {
            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 (ProtocolException 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();
    }
}

//MAinAdapter 主要條目佈局
package com.example.day08_test02.Adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.day08_test02.Bean.MyimagerBean;
import com.example.day08_test02.Bean.MynewsBean;
import com.example.day08_test02.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;

public class MyAdapter extends BaseAdapter {

//定義三個值 一個 代表條目總數
private final int ITEM_COUNT = 2;
private final int IMAGE_TYPE = 0;
private final int NEWS_TYPE = 1;
//
private Context context;
private List<MynewsBean.Result> News_list;
private List<MyimagerBean.Data> Image_List;


//初始化的東西
public MyAdapter(Context context) {
    this.context = context;
    News_list = new ArrayList<>();
    Image_List = new ArrayList<>();
}

//003更新圖片
public void setImage(List<MyimagerBean.Data> images){
    //先清空
    Image_List.clear();
    //在判斷
    if(images!=null){
        //在新增
        Image_List.addAll(images);
    }
    notifyDataSetChanged();
}

//002更新的新聞資料
public void setDatas(List<MynewsBean.Result> lists){
    if(lists!=null){
        News_list.clear();
        News_list.addAll(lists);
    }
    notifyDataSetChanged();
}
//001追加的新聞資料
public void addDatas(List<MynewsBean.Result> lists){
    //判斷傳過來的資料不是空
    if(lists!=null){
        //讓news + 進去
        News_list.addAll(lists);
    }
    notifyDataSetChanged();
}

//判斷載入沒載入圖片
private Boolean hasImage(){
    return Image_List.size()>0;
}


//得到試圖 的數量 也就是載入幾種條目數
// 手寫方法01
@Override
public int getViewTypeCount() {

    return ITEM_COUNT;

}

//得到試圖的型別
// 手寫方法  02
@Override
public int getItemViewType(int position) {
    //如果載入了圖片就從1開始 沒有就從0開始
    //因為總試圖是兩個 載入了圖片才能從0-2,但是沒載入圖片所以是1-2
    return position==0&hasImage() ?IMAGE_TYPE:NEWS_TYPE;
}


//01
//這裡展示的是新聞的總條目
@Override
public int getCount() {
    //如果不展示另一個 就是
    //return News_list.size();
    //但是現在不是 判斷第一個加載出來沒有
    //加載出來下標就+1  沒有就原位置
    return hasImage() ? News_list.size()+1:News_list.size();
}

//02
//這裡展示的是新聞的東西
@Override
public MynewsBean.Result getItem(int position) {
    //判斷圖片載入與否
    return News_list.get(hasImage()?position-1:position);
}

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

//04
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    //開局判斷 是 新聞還是圖片
    if(getItemViewType(position)==NEWS_TYPE){
        NewsViewHolder viewHolder;
        if(convertView==null){
            //載入試圖
            convertView = LayoutInflater.from(context).inflate(R.layout.news_list,parent,false);
            //例項化暫存器
            viewHolder = new NewsViewHolder(convertView);

        }else{
            viewHolder = (NewsViewHolder) convertView.getTag();
        }
        //呼叫 暫存器裡面的方法
        viewHolder.bindData(getItem(position));
    }else{
        //圖片寄存
        ImagerViewHolder imagerViewHolder;
        if(convertView==null){
            convertView =LayoutInflater.from(context).inflate(R.layout.image_list, parent, false);
            imagerViewHolder = new ImagerViewHolder(convertView);

        }else{
            imagerViewHolder = (ImagerViewHolder) convertView.getTag();
        }
        //呼叫方法 因為圖片輪播的是在這裡進行
        imagerViewHolder.bindData(context,Image_List);
    }
    return convertView;
}

//新聞的暫存器
class NewsViewHolder{

    ImageView icon;
    TextView summary;
    TextView name;

    //為自己構造有參 引數為試圖  用來findById
    public NewsViewHolder(View view){
        icon = view.findViewById(R.id.image01);
        name = view.findViewById(R.id.name01);
        summary = view.findViewById(R.id.title01);
        //settag
        view.setTag(this);
    }
    //賦值的方法 例項化本類 可以調這個方法 用來賦值
    public void bindData(MynewsBean.Result item) {
        name.setText(item.getName());
        summary.setText(item.getSummary());
        //用ImageLoader來載入圖片
        ImageLoader.getInstance().displayImage(item.getImageUrl(), icon);

    }
}

//圖片的暫存器
class ImagerViewHolder{
    //載入ViewPager
    ViewPager viewPager;

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


    //findByid
    public ImagerViewHolder(View view){
        viewPager = view.findViewById(R.id.pager);
        view.setTag(this);
    }


    //賦值
    public void bindData(Context context, List<MyimagerBean.Data> image){
        //清空所有任務資訊
        handler.removeCallbacksAndMessages(null);
        //設定介面卡
        viewPager.setAdapter(new MyimageAdapter(image,context));

        viewPager.setCurrentItem(viewPager.getAdapter().getCount()/2);

        handler.sendEmptyMessageDelayed(0,2000);
    }

}

}
// PagerApater

package com.example.day08_test02.Adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.day08_test02.Bean.MyimagerBean;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.Date;
import java.util.List;

public class MyimageAdapter extends PagerAdapter {

    private List<MyimagerBean.Data> list;
    private Context context;

    public MyimageAdapter(List<MyimagerBean.Data> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @Override
    public int getCount() {
        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);
        Log.i("TAG",list.size()+"");
        ImageLoader.getInstance().displayImage(list.get(position%list.size()).getUrlNoHttps(),imageView);


        return imageView;

    }

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