TabLayout+PullToRefreshListView上拉刷新,下拉加载,imageloader自定义

主类布局(TabLayout需要道包design)

<?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"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"

        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:tabGravity="center"
        app:tabIndicatorColor="#ff0000"
        app:tabMode="scrollable"

        app:tabSelectedTextColor="#ff0000"
        app:tabTextColor="#00ff00">

    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_below="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</RelativeLayout>

主类的内容

package com.example.a18_zhoukao_test;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> titleList;

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

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        viewPager = (ViewPager) findViewById(R.id.view_pager);

        titleList = new ArrayList<>();
        titleList.add("福利");
        titleList.add("Android");
        titleList.add("IOS");
        titleList.add("休息视频");
        titleList.add("拓展资源");
        titleList.add("前端");
        titleList.add("all");

        /**
         * viewPager需要设置容器中装的页面数量,默认是三页,,,否则在切换的时候前面的再切换回来就不显示了
         */

        viewPager.setOffscreenPageLimit(titleList.size());

        //设置适配器
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public CharSequence getPageTitle(int position) {
                //展示的标题
                return titleList.get(position);
            }

            @Override
            public Fragment getItem(int position) {
                //....fragment集合viewPager使用的时候,fragment是new出来的
                NewsFragment newsFragment = new NewsFragment();

                Bundle bundle = new Bundle();

                //把当前位置的标题传递过去
                bundle.putString("name",titleList.get(position));

                newsFragment.setArguments(bundle);

                return newsFragment;
            }

            @Override
            public int getCount() {
                return titleList.size();
            }
        });

        //绑定在一起
        tabLayout.setupWithViewPager(viewPager);

    }
}

NewsFragment类布局PullToRefreshListView需要从外部道入一个liarble包

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/refresh_list_view"
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF" >

    </com.handmark.pulltorefresh.library.PullToRefreshListView>

</LinearLayout>

NewsFragment

package com.example.a18_zhoukao_test;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dash
 * @date 2017/9/18
 * @description:
 */
public class NewsFragment extends Fragment {


    private View view;
    private PullToRefreshListView refreshListView;
    private String param;
    private String path;
    private int page_num = 1;
    private List<DataDataBean.ResultsBean> list = new ArrayList<>();
    private MyAdapter myAdapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_layout,container,false);

        refreshListView = (PullToRefreshListView) view.findViewById(R.id.refresh_list_view);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle bundle = getArguments();
        param = bundle.getString("name", "Android");


        //请求数据,,,设置适配器
        getData();

        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);

        ILoadingLayout startLabels = refreshListView.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新");
        startLabels.setRefreshingLabel("正在刷新...");
        startLabels.setReleaseLabel("放开刷新");
        ILoadingLayout endLabels = refreshListView.getLoadingLayoutProxy( false, true);
        endLabels.setPullLabel("上拉刷新");
        endLabels.setRefreshingLabel("正在载入...");
        endLabels.setReleaseLabel("放开刷新...");

        //设置监听
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getRefreshData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉加载的时候 page_num加一
                page_num ++;
                getData();
            }
        });
    }

    /**
     * 获取刷新时的数据...刷新时只访问第一页的数据,,,,刷新的数据需要添加到集合的前边
     *
     * 刷新完成,,设置适配器之后刷新需要停止
     */

    private void getRefreshData() {

        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {

                try {
                    String path = "http://gank.io/api/data/"+ URLEncoder.encode(param,"utf-8")+"/10/1";

                    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 s) {
                //解析
                Gson gson = new Gson();

                DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class);

                /**
                 * 判断数据非空
                 */

                if (dataDataBean != null && dataDataBean.getResults() != null){
                    //数据添加
                    list.addAll(0,dataDataBean.getResults());

                    //设置适配器
                    setAdapter();

                    //停止刷新
                    refreshListView.onRefreshComplete();
                }

            }
        };

        asyncTask.execute();
    }

    /**
     * 这个方法是刚进入界面的时候请求数据,,,,和上拉加载的时候不停的请求数据
     *
     * page_num每次加载的时候会加1,,,这个方法中数据添加在list集合的后面
     *
     * 请求设置适配器之后 刷新停止
     */

    private void getData() {

        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {

                try {
                    String path = "http://gank.io/api/data/"+ URLEncoder.encode(param,"utf-8")+"/10/"+page_num;

                    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 s) {
                //解析
                Gson gson = new Gson();

                DataDataBean dataDataBean = gson.fromJson(s, DataDataBean.class);


                /**
                 * 判断数据非空
                 */

                if (dataDataBean != null && dataDataBean.getResults() != null){
                    //数据添加
                    list.addAll(dataDataBean.getResults());//拿到的是每一页的数据的集合

                    //设置适配器
                    setAdapter();


                    //刷新停止
                    refreshListView.onRefreshComplete();
                }

            }
        };

        asyncTask.execute();

    }

    private void setAdapter() {
        if (myAdapter == null){

            myAdapter = new MyAdapter(getActivity(),list);
            refreshListView.setAdapter(myAdapter);
        }else {
            myAdapter.notifyDataSetChanged();
        }

    }

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

MyAdapter适配布局

<?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"
    android:orientation="horizontal"
    android:padding="10dp">

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

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

</LinearLayout>

MyAdaptr适配

package com.example.a18_zhoukao_test;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * @author Dash
 * @date 2017/9/18
 * @description:
 */
public class MyAdapter extends BaseAdapter {
    Context context;
    List<DataDataBean.ResultsBean> list;

    public MyAdapter(Context context, List<DataDataBean.ResultsBean> 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 View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if (view == null){
            view  = View.inflate(context,R.layout.item_layout,null);

            holder = new ViewHolder();

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

            view.setTag(holder);

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

        //设置
        holder.textView.setText(list.get(i).getDesc());
        /**
         * 加载图片之前需要判断一下是否有图片的地址
         */

        if (list.get(i).getImages() != null){
            ImageLoader.getInstance().displayImage(list.get(i).getImages().get(0)+"?imageView2/0/w/100",holder.imageView,ImageLoaderUtil.getDefaultOption());
        }



        return view;
    }

    private class ViewHolder{
        ImageView imageView;
        TextView textView;
    }
}

Imageloader工具类(自定义)需要道包nostra
import android.content.Context;
import android.graphics.Bitmap;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;

/**
 * @author Dash
 * @date 2017/9/18
 * @description:
 */
public class ImageLoaderUtil {
    /**
     * 初始化的方法
     *
     * @param
     */

    public static void init(Context context) {

        File cacheDir = StorageUtils.getCacheDirectory(context);  //缓存文件夹路径
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)

                .threadPoolSize(3) // default  线程池内加载的数量
                .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 getDefaultOption() {
        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.IN_SAMPLE_POWER_OF_2) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型

                .displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)

                .build();

        return options;
    }
}

BaseApplication创建类

public class BaseApplication extends Application {

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

        ImageLoaderUtil.init(this);
    }
}







展开阅读全文

没有更多推荐了,返回首页