热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

XListView+ViewPager+上拉下拉

布局:<?xmlversion1.0encodingutf-8?><RelativeLayoutxmlns:androidhttp:sch

布局:


    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_>

   
        android:id="@+id/x_listview"
        android:layout_
        android:layout_ />

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


    android:orientation="horizontal"
    android:layout_
    android:layout_>

            android:id="@+id/image_view"
        android:layout_
        android:layout_ />

            android:layout_
        android:layout_
        android:id="@+id/text_title"
        />

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


    android:layout_
    android:layout_>

            android:layout_
        android:layout_
        android:id="@+id/text_title"
        />

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

主页面:

public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {

    private XListView xListView;
    private int page = 1;

    //装页面展示所有数据的集合
    private List 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 asyncTask = new AsyncTask() {
            @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 asyncTask = new AsyncTask() {
            @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 list;

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

    public MyAdapter(Context context, List 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;
    }
}


推荐阅读
author-avatar
mobiledu2502852753
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有