PullToRefreshScrollView的使用 +Banner

移动开发 waitig 504℃ 百度已收录 0评论
package com.example.a08yuekao.fragment;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.a08yuekao.MyImageLoader;
import com.example.a08yuekao.R;
import com.example.a08yuekao.Result;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.youth.banner.Banner;

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

/**
 * Created by Administrator on 2017/10/23.
 */

public class SyFragment extends Fragment {

    //private PullToRefreshListView pull_lv;
    private Handler handler = new Handler();
    private String str = "";
    private List<Result.DataBean.ComicsBean> newslist;
    private MyAdapter myAdapter;
    private int pageIndex = 1;
    private List<String> data = new ArrayList<>();
    private Banner bann;
    private PullToRefreshScrollView rsv;
    private DisplayImageOptions options;
    private ListView lv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sy, null);
        bann = (Banner) view.findViewById(R.id.bann);
        lv = (ListView) view.findViewById(R.id.lv);
        rsv = (PullToRefreshScrollView) view.findViewById(R.id.refresh_scroll_view);

        new MyAsync().execute("http://api.kkmh.com/v1/daily/comic_lists/0?since=" + pageIndex + "&gender=" + pageIndex + "&sa_event=eyJwcm9qZWN0Ijoia3VhaWthbl9hcHAiLCJ0aW1lIjoxNDg3NzQyMjQwNjE1LCJwcm9wZXJ0aWVzIjp7IkhvbWVwYWdlVGFiTmFtZSI6IueDremXqCIsIlZDb21tdW5pdHlUYWJOYW1lIjoi54Ot6ZeoIiwiJG9zX3ZlcnNpb24iOiI0LjQuMiIsIkdlbmRlclR5cGUiOiLlpbPniYgiLCJGcm9tSG9tZXBhZ2VUYWJOYW1lIjoi54Ot6ZeoIiwiJGxpYl92ZXJzaW9uIjoiMS42LjEzIiwiJG5ldHdvcmtfdHlwZSI6IldJRkkiLCIkd2lmaSI6dHJ1ZSwiJG1hbnVmYWN0dXJlciI6ImJpZ25veCIsIkZyb21Ib21lcGFnZVVwZGF0ZURhdGUiOjAsIiRzY3JlZW5faGVpZ2h0IjoxMjgwLCJIb21lcGFnZVVwZGF0ZURhdGUiOjAsIlByb3BlcnR5RXZlbnQiOiJSZWFkSG9tZVBhZ2UiLCJGaW5kVGFiTmFtZSI6IuaOqOiNkCIsImFidGVzdF9ncm91cCI6MTEsIiRzY3JlZW5fd2lkdGgiOjcyMCwiJG9zIjoiQW5kcm9pZCIsIlRyaWdnZXJQYWdlIjoiSG9tZVBhZ2UiLCIkY2FycmllciI6IkNoaW5hIE1vYmlsZSIsIiRtb2RlbCI6IlZQaG9uZSIsIiRhcHBfdmVyc2lvbiI6IjMuNi4yIn0sInR5cGUiOiJ0cmFjayIsImRpc3RpbmN0X2lkIjoiQTo2YWRkYzdhZTQ1MjUwMzY1Iiwib3JpZ2luYWxfaWQiOiJBOjZhZGRjN2FlNDUyNTAzNjUiLCJldmVudCI6IlJlYWRIb21lUGFnZSJ9");

        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)//进行内存缓存
                .cacheOnDisk(true)//进行sd卡缓存
                /*.showImageOnLoading(R.drawable.ic_stub) // 设置正在下载中的图片
                .showImageForEmptyUri(R.drawable.ic_empty) //没有请求地址时
                .showImageOnFail(R.drawable.ic_error)//下载错误时*/
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片质量
                .build();
        initLV();
        return view;
    }

    private void initLV() {


        //1.设置模式
        rsv.setMode(PullToRefreshBase.Mode.BOTH);

        //2.通过调用getLoadingLayoutProxy方法,设置下拉刷新状况布局中显示的文字 ,第一个参数为true,代表下拉刷新
        ILoadingLayout headLables = rsv.getLoadingLayoutProxy(true, false);
        headLables.setPullLabel("下拉刷新");
        headLables.setRefreshingLabel("正在刷新");
        headLables.setReleaseLabel("松开刷新");

        //2.设置上拉加载底部视图中显示的文字,第一个参数为false,代表上拉加载更多
        ILoadingLayout footerLables = rsv.getLoadingLayoutProxy(false, true);
        footerLables.setPullLabel("上拉加载");
        footerLables.setRefreshingLabel("正在载入...");
        footerLables.setReleaseLabel("松开加载更多");

        //3.设置监听事件
        rsv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                addToTop();//请求网络数据,并更新listview组件
                refreshComplete();//数据加载完成后,关闭header,footer
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                addToBottom();//请求网络数据,并更新listview组件
                refreshComplete();//数据加载完成后,关闭header,footer
            }
        });
    }


    /**
     * 刷新完成时关闭
     */

    private void addToBottom() {
        pageIndex++;
        new MyAsync().execute("http://api.kkmh.com/v1/daily/comic_lists/0?since="+pageIndex+"&gender=0&sa_event=eyJwcm9qZWN0Ijoia3VhaWthbl9hcHAiLCJ0aW1lIjoxNDg3NzQyMjQwNjE1LCJwcm9wZXJ0aWVzIjp7IkhvbWVwYWdlVGFiTmFtZSI6IueDremXqCIsIlZDb21tdW5pdHlUYWJOYW1lIjoi54Ot6ZeoIiwiJG9zX3ZlcnNpb24iOiI0LjQuMiIsIkdlbmRlclR5cGUiOiLlpbPniYgiLCJGcm9tSG9tZXBhZ2VUYWJOYW1lIjoi54Ot6ZeoIiwiJGxpYl92ZXJzaW9uIjoiMS42LjEzIiwiJG5ldHdvcmtfdHlwZSI6IldJRkkiLCIkd2lmaSI6dHJ1ZSwiJG1hbnVmYWN0dXJlciI6ImJpZ25veCIsIkZyb21Ib21lcGFnZVVwZGF0ZURhdGUiOjAsIiRzY3JlZW5faGVpZ2h0IjoxMjgwLCJIb21lcGFnZVVwZGF0ZURhdGUiOjAsIlByb3BlcnR5RXZlbnQiOiJSZWFkSG9tZVBhZ2UiLCJGaW5kVGFiTmFtZSI6IuaOqOiNkCIsImFidGVzdF9ncm91cCI6MTEsIiRzY3JlZW5fd2lkdGgiOjcyMCwiJG9zIjoiQW5kcm9pZCIsIlRyaWdnZXJQYWdlIjoiSG9tZVBhZ2UiLCIkY2FycmllciI6IkNoaW5hIE1vYmlsZSIsIiRtb2RlbCI6IlZQaG9uZSIsIiRhcHBfdmVyc2lvbiI6IjMuNi4yIn0sInR5cGUiOiJ0cmFjayIsImRpc3RpbmN0X2lkIjoiQTo2YWRkYzdhZTQ1MjUwMzY1Iiwib3JpZ2luYWxfaWQiOiJBOjZhZGRjN2FlNDUyNTAzNjUiLCJldmVudCI6IlJlYWRIb21lUGFnZSJ9");
    }

    public void refreshComplete() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                rsv.onRefreshComplete();
            }
        }, 1000);
    }


    private void addToTop() {
        pageIndex--;
        new MyAsync().execute("http://api.kkmh.com/v1/daily/comic_lists/0?since="+pageIndex+"&gender=0&sa_event=eyJwcm9qZWN0Ijoia3VhaWthbl9hcHAiLCJ0aW1lIjoxNDg3NzQyMjQwNjE1LCJwcm9wZXJ0aWVzIjp7IkhvbWVwYWdlVGFiTmFtZSI6IueDremXqCIsIlZDb21tdW5pdHlUYWJOYW1lIjoi54Ot6ZeoIiwiJG9zX3ZlcnNpb24iOiI0LjQuMiIsIkdlbmRlclR5cGUiOiLlpbPniYgiLCJGcm9tSG9tZXBhZ2VUYWJOYW1lIjoi54Ot6ZeoIiwiJGxpYl92ZXJzaW9uIjoiMS42LjEzIiwiJG5ldHdvcmtfdHlwZSI6IldJRkkiLCIkd2lmaSI6dHJ1ZSwiJG1hbnVmYWN0dXJlciI6ImJpZ25veCIsIkZyb21Ib21lcGFnZVVwZGF0ZURhdGUiOjAsIiRzY3JlZW5faGVpZ2h0IjoxMjgwLCJIb21lcGFnZVVwZGF0ZURhdGUiOjAsIlByb3BlcnR5RXZlbnQiOiJSZWFkSG9tZVBhZ2UiLCJGaW5kVGFiTmFtZSI6IuaOqOiNkCIsImFidGVzdF9ncm91cCI6MTEsIiRzY3JlZW5fd2lkdGgiOjcyMCwiJG9zIjoiQW5kcm9pZCIsIlRyaWdnZXJQYWdlIjoiSG9tZVBhZ2UiLCIkY2FycmllciI6IkNoaW5hIE1vYmlsZSIsIiRtb2RlbCI6IlZQaG9uZSIsIiRhcHBfdmVyc2lvbiI6IjMuNi4yIn0sInR5cGUiOiJ0cmFjayIsImRpc3RpbmN0X2lkIjoiQTo2YWRkYzdhZTQ1MjUwMzY1Iiwib3JpZ2luYWxfaWQiOiJBOjZhZGRjN2FlNDUyNTAzNjUiLCJldmVudCI6IlJlYWRIb21lUGFnZSJ9");


    }

    class MyAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //创建Url对象
            try {
                URL url = new URL(params[0]);
                //打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //设置
                connection.setRequestMethod("GET");
                connection.setReadTimeout(3000);
                connection.setConnectTimeout(3000);
                int code = connection.getResponseCode();
                if (code == 200) {
                    InputStream inputStream = connection.getInputStream();
                    str = streamToString(inputStream);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e("ZZZ", s + "11111111111111111");
            //解析数据
            Gson gson = new Gson();
            Result result = gson.fromJson(str, Result.class);
            newslist = result.getData().getComics();
            for (int i=0;i<newslist.size();i++){
                data.add(newslist.get(i).getCover_image_url());
            }
            //设置banner样式
            // banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
            //设置图片加载器
            bann.setImageLoader(new MyImageLoader());
            //设置图片集合
            bann.setImages(data);
            //设置banner动画效果
            //banner.setBannerAnimation(Transformer.RotateDown);
            //设置标题集合(当banner样式有显示title时)
            //banner.setBannerTitles(imageTitle);
            //设置轮播时间
            bann.setDelayTime(1500);
            //设置指示器位置(当banner模式中有指示器时)
            //banner.setIndicatorGravity(BannerConfig.CENTER);
            //banner设置方法全部调用完毕时最后调用
            bann.start();
            setAdapter();


        }

    }

    private void setAdapter() {

        if (myAdapter == null) {
            myAdapter = new MyAdapter();
            lv.setAdapter(myAdapter);
        } else {
            myAdapter.notifyDataSetChanged();
        }
    }

    public String streamToString(InputStream is) {
        StringBuilder sb = new StringBuilder();
        String con;
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        try {
            while ((con = br.readLine()) != null) {
                sb.append(con);
            }
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }

        return sb.toString();

    }

    class MyAdapter extends BaseAdapter {

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

        @Override
        public Object getItem(int position) {
            return newslist.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getActivity(), R.layout.item, null);
            ImageView img = (ImageView) view.findViewById(R.id.img);
            TextView tv = (TextView) view.findViewById(R.id.tv);

            ImageLoader.getInstance().displayImage(newslist.get(position).getCover_image_url(), img, options);
            tv.setText(newslist.get(position).getTitle());
            return view;
        }
    }
}
//自定义View继承ListView 解决与Banner的冲突问题
package com.example.a08yuekao;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * Created by Administrator on 2017/10/24.
 */

public class Zdy extends ListView {

    public Zdy(Context context) {
        super(context);
    }

    public Zdy(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Zdy(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);

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



    <com.handmark.pulltorefresh.library.PullToRefreshScrollView
        android:id="@+id/refresh_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF">

        <!--在scrollView中添加组件 viewPager和ListView
            注意:在scrollView中只能有一个子孩子-->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >
            <com.youth.banner.Banner
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:id="@+id/bann"
                ></com.youth.banner.Banner>
            <com.example.a08yuekao.Zdy
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/lv"
                ></com.example.a08yuekao.Zdy>
        </LinearLayout>

    </com.handmark.pulltorefresh.library.PullToRefreshScrollView>
</LinearLayout>


本文由【waitig】发表在等英博客
本文固定链接:PullToRefreshScrollView的使用 +Banner
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)