XListView+ViewPager+上拉下拉

来源:互联网 发布:短信验证码 java 编辑:程序博客网 时间:2024/05/14 11:39

布局:

<?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">

    <com.example.a11_zhoukao_test.view.XListView

        android:id="@+id/x_listview"
        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:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_title"
        />

</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">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text_title"
        />

</LinearLayout>

=========================

主页面:

public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {

    private XListView xListView;
    private int page = 1;

    //装页面展示所有数据的集合
    private List<DataDataBean.DataBean> list = new ArrayList<>();
    private MyAdapter myAdapter;


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

        xListView = (XListView) findViewById(R.id.x_listview);

        //设置
        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);

        //获取网络上的数据
        getDataFromNet();

        //设置监听
        xListView.setXListViewListener(this);

    }

    /**
     * 获取网络数据
     */
    private void getDataFromNet() {
        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {

                String path = "http://www.yulin520.com/a2a/impressApi/news/mergeList?pageSize=10&page="+page;
                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();
                DataDataBean dataDataBean = gson.fromJson(json, DataDataBean.class);


                //添加
                list.addAll(dataDataBean.getData());

                //设置适配器
                setAdapter();

                //加载完成之后
                xListView.stopLoadMore();
            }
        };

        asyncTask.execute();

    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        if (myAdapter == null){

            myAdapter = new MyAdapter(MainActivity.this,list);
            xListView.setAdapter(myAdapter);
        }else {
            myAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        getRefreshData();
    }

    private void getRefreshData() {
        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                //下拉刷新的时候之请求第一页的数据
                String path = "http://www.yulin520.com/a2a/impressApi/news/mergeList?pageSize=10&page=1";
                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();
                DataDataBean dataDataBean = gson.fromJson(json, DataDataBean.class);


                //添加
                list.addAll(0,dataDataBean.getData());

                //设置适配器
                setAdapter();

                //刷新完成之后
                xListView.stopRefresh();
                xListView.setRefreshTime("刚刚");
            }
        };

        asyncTask.execute();
    }

    /**
     * 上拉加载更多
     */
    @Override
    public void onLoadMore() {
        page ++;
        getDataFromNet();
    }

    private String streamToString(InputStream inputStream,String charset) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String s = null;
            StringBuilder builder = new StringBuilder();
            while ((s = bufferedReader.readLine()) != null){
                builder.append(s);
            }

            bufferedReader.close();
            return builder.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return  null;
    }
}

=================================================================================

Adapter页面:

public class MyAdapter extends BaseAdapter {
    Context context;
    List<DataDataBean.DataBean> list;

    private int IMAGE = 0;
    private int TITLE = 1;

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

    @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;
    }

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

    @Override
    public int getItemViewType(int position) {
        if (position%2 == 0){
            return IMAGE;
        }

        return TITLE;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (getItemViewType(i) == IMAGE){
            ImageHolder holder;
            if (view == null){
                view = View.inflate(context, R.layout.image_layout,null);
                holder = new ImageHolder();

                holder.textView = view.findViewById(R.id.text_title);
                holder.imageView = view.findViewById(R.id.image_view);

                view.setTag(holder);

            }else {
                holder = (ImageHolder) view.getTag();
            }

            //赋值
            holder.textView.setText(list.get(i).getTitle());
            //图片
            ImageLoader.getInstance().displayImage(list.get(i).getImg(),holder.imageView, ImageLoaderUtil.getOption());


        }else {
            TextHolder holder;
            if (view == null){
                view = View.inflate(context, R.layout.title_layout,null);
                holder = new TextHolder();

                holder.textView = view.findViewById(R.id.text_title);

                view.setTag(holder);

            }else {
                holder = (TextHolder) view.getTag();
            }

            //赋值
            holder.textView.setText(list.get(i).getTitle());

        }


        return view;//空指针异常....obtainView()
    }

    private class ImageHolder{
        ImageView imageView;
        TextView textView;
    }
    private class TextHolder{
        TextView textView;
    }
}

======================================================

APPlication页面:

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        //配置
        ImageLoaderUtil.initConfig(this);
    }
}

=======================================================

ImageLoaderUtil页面:

public class ImageLoaderUtil {
    /**
     * 配置的方法
     * @param context
     */
    public static void initConfig(Context context) {

        File cacheDir = new File(Environment.getExternalStorageDirectory(),"/image");  //缓存文件夹路径

        if (!cacheDir.exists()){
            cacheDir.mkdirs();
        }

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径
                .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
                .diskCacheFileCount(100)  // 可以缓存的文件数量
                // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .imageDownloader(new BaseImageDownloader(context)) // default
                .imageDecoder(new BaseImageDecoder(true)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs() // 打印debug log
                .build(); //开始构建

        ImageLoader.getInstance().init(config);

    }


    public static DisplayImageOptions getOption() {

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(1000)  // 下载前的延迟时间
                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中

                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
                .build();

        return options;
    }
}

原创粉丝点击