Android动态加载轮播图BannerView

轮播图在每个app中扮演着一个点缀的角色,在独立做了三款app后都有这个需求,所以我决定把它单独抽出来。以后只需copy,然后再根据需求改一下即可。
Android动态加载轮播图BannerView_第1张图片

/**
 * 加载网络轮播图
 *@author jiangrongtao
 *
 *csdn:http://blog.csdn.net/jiang_rong_tao
 *
 *github:https://github.com/jiangrongtao/jiangrongtao.github.io
 *
 * created at 2016/6/3 9:14
*/


public class BannerView {
    private View bannerView;
    private Context mContext;
    private Map maps;
    private FragmentManager manager;
    private List mList;
    private MyChildViewPager bannerPager;
    private ImageView defImage;//设置默认图片
    public  static boolean LOAD_FINISH=false;//是成功加载banner
    private LinearLayout llDots;//下部的小白点的布局
    public  boolean isRoll = false;//是否轮播
    private List dotList = new ArrayList();//存放小白点

    private static final String TAG = "BannerView";
    public BannerView(Context context,Map maps,FragmentManager manager){
        this.mContext=context;
        this.maps=maps;
        this.manager=manager;
        mList=new ArrayList();
    }
    protected Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    final List data = (List) msg.obj;
                    setBannerInfo(data);
                    break;
                case 2:
                    LOAD_FINISH=false;
                    defImage.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    if (mList.size() > 0) {
                        bannerPager.setCurrentItem((bannerPager.getCurrentItem() + 1) % mList.size());
                    } else {
                        isRoll = false;
                    }
                    break;
            }
        }
    };

    /**
     * 设置banner信息
     * @param data
     */
    private void setBannerInfo(final List data) {
        mList.clear();
        for (int i = 0; i < data.size(); i++) {
            final int j = i;
            final ImageView imageView = new ImageView(mContext);
            BannerInfo bannerInfo = data.get(i);
            APIImageLoader.displayImage(mContext,bannerInfo.getUrl(), R.drawable.banner_fial,R.drawable.banner_fial,imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
             @Override
                public void onClick(View v) {
                    String hrefUrl = data.get(j).getHrefUrl();
                    if (!TextUtils.isEmpty(hrefUrl)) {
                        Intent intent = new Intent(mContext, AppDetailActivity.class);
                        intent.putExtra("hrefUrl", hrefUrl);
                        mContext.startActivity(intent);
                    }
                }
            });
            Fragment fragment = new Fragment() {
                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                         Bundle savedInstanceState) {
                    return imageView;
                }
            };
            mList.add(fragment);
        }
        if(mList.size()>0){
            defImage.setVisibility(View.GONE);
            bannerPager.setAdapter(new BannerAdapter(manager, mList));
            initDot();
            bannerPager.setCurrentItem(0);
            LOAD_FINISH=true;
        }else{
            LOAD_FINISH=false;
            defImage.setVisibility(View.VISIBLE);
        }
    }

    public View getBannerView() {
        bannerView=View.inflate(mContext, R.layout.banner_layout,null);
        bannerPager= (MyChildViewPager) bannerView.findViewById(R.id.banner_pager);
        defImage = (ImageView)bannerView.findViewById(R.id.iv_default_page);
        llDots=(LinearLayout)bannerView.findViewById(R.id.ll_dots);
        initBannersData();
        return bannerView;
    }
    /*
    * 设置循环轮播
    * */
    public void setBannerCycle(long loopTime){

        if(LOAD_FINISH){
            if(null!=bannerPager){
                isRoll=true;
                startLooper(loopTime);
                bannerPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        switchDot(position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }
    }

    /**
     * 开启轮播
     * @param loopTime 轮播间隔时间
     */
    private void startLooper(final long loopTime) {

        new Thread() {
            public void run() {
                while (isRoll) {
                   handler.sendEmptyMessageDelayed(3,loopTime);
                }
            };
        }.start();
    }

    //获取网络banner图片
    private void initBannersData() {
        maps.clear();
        RequestManager.getInstance(mContext).sendPost(APIConfig.GET_BANNERS, maps, BannerRes.class, new Callback() {
            @Override
            public BannerRes parseNetworkResponse(Response response) throws Exception {
                return  GsonUtils.object(response.body().string(),BannerRes.class);
            }

            @Override
            public void onError(Call call, Exception e) {

            }

            @Override
            public void onResponse(BannerRes response) {

                if(APIResCode.SUCCESS.equals(response.getResCode())){
                    List data = response.getData();
                    if (data!=null&&data.size()>0){
                        handler.sendMessage(handler.obtainMessage(1, data));
                    }else{
                        handler.sendEmptyMessage(2);
                    }
                }
            }
        });
    }
    /**
     * 初始化小圆点
     */
    private void initDot() {
        llDots.removeAllViews();
        dotList.clear();
        for (int i = 0; i < mList.size(); i++) {
            View view = new View(mContext);
            //默认选中第一个小白点
            view.setBackgroundResource(i == 0?R.drawable.dot_sel:R.drawable.dot_nor);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(8, 8);
            params.setMargins(0, 0, 12, 0);
            llDots.addView(view, params);
            dotList.add(view);
        }
    }
    /**
     * 切换圆点
     */
    private void switchDot(int position) {
        for (int i = 0; i < dotList.size(); i++) {
            dotList.get(i).setBackgroundResource(i == position?R.drawable.dot_sel:R.drawable.dot_nor);
        }
    }
}

轮播图适配器:

public class BannerAdapter extends FragmentPagerAdapter{
    List list ;
    public BannerAdapter(FragmentManager fm, List list) {
        super(fm);
        this.list = list ;
    }
    @Override
    public  Fragment getItem(int index) {
        return list.get(index%list.size());
    }
    @Override
    public int getCount() {
        return list.size();
    }
}

布局文件:

"1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
    <com.jianzhilaila.money.ui.view.myviewpager.MyChildViewPager
        android:id="@+id/banner_pager"
        android:layout_width="match_parent"
        android:layout_height="200dp">
    com.jianzhilaila.money.ui.view.myviewpager.MyChildViewPager>
    "@+id/iv_default_page"
        android:layout_width="match_parent"
        android:layout_height="208dp"
        android:background="@drawable/banner_fial" />
    "@+id/ll_dots"
    android:layout_width="match_parent"
    android:layout_height="8dp"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:layout_gravity="bottom"
    android:layout_marginBottom="10dp"
    android:orientation="horizontal" />

具体用法

//获取banner
 BannerView bannerView = new BannerView(context, maps,   getChildFragmentManager());
        View banner = bannerView.getBannerView();
        mLinearLayout.addView(banner,0);
        bannerView.setBannerCycle(1500);
在onDestroyView()或onDestroy()中记得设置:**isRoll=false;** ,避免内存溢出。
mLinearLayout是轮播图页面的根布局。getChildFragmentManager是由于我的Viewpager是嵌套使用的。MyChildViewPager 是一个自定义的防止嵌套使用滑动事件冲突的类。RequestManager和APIImageLoader是我自己二次封装的网络请求和图片加载类,在我以前的博客http://blog.csdn.net/jiang_rong_tao/article/details/51516977中。

注意:上面代码有很多要改进的地方,如果有bug自己修复,可以把改进的代码分享一下。

你可能感兴趣的:(android)