自定义轮播图

一、自定义Banner控件的布局

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

<android.support.v4.view.ViewPager
    android:id="@+id/custom_vp"
    android:layout_width="match_parent"
    android:layout_height="200dp">

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

<LinearLayout
    android:id="@+id/custom_ll"
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:layout_alignBottom="@id/custom_vp"
    android:gravity="center"
    android:orientation="horizontal">

</LinearLayout>
</RelativeLayout>

二、需要自己绘制小圆点

(未选中状态)shape_cirlce_norml

<?xml version="1.0" encoding="utf-8"?>
<!--绘制未选中状态下的图案,为圆形-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <!--宽高分别为20dp-->
    <size android:height="10dp" android:width="10dp"></size>
    <!--灰色代表未选中状态-->
    <solid android:color="#55999999"></solid>

</shape>

(选中状态)shape_cirlce_selected

<?xml version="1.0" encoding="utf-8"?>
<!--绘制选中状态下的图案,为圆形-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <!--宽高分别为20dp-->
    <size android:height="10dp" android:width="10dp"></size>
    <!--红色代表选中-->
    <solid android:color="#ff00"></solid>

</shape>

(判断是否是选中状态 )circle_selector

<?xml version="1.0" encoding="utf-8"?>
<!--判断小圆点的选中状态-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--当state_selected为true时,判断为选中状态-->
    <item android:drawable="@drawable/shape_cirlce_selected" android:state_selected="true"></item>
    <!--当state_selected为false时,判断为未选中状态-->
    <item android:drawable="@drawable/shape_cirlce_norml" android:state_selected="false"></item>
</selector>

三、自定义Banner的代码

package com.bwei.lenovo.day11_myapp.customView;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bwei.lenovo.day11_myapp.R;
import com.bwei.lenovo.day11_myapp.bean.ShowYeBean;

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

/**
 * Created by lenovo on 2018/3/21.
 * 自定义banner
 */

public class MyBannerView extends RelativeLayout {
    private static String TAG = "Banner-----------";
    //轮播图片集合 list
    private static List<ImageView> list;
    private static List<ImageView> points = new ArrayList<>();
    private static ViewPager custom_vp;
    private static LinearLayout custom_ll;
    private MyHandler myHandler = new MyHandler();

    public MyBannerView(Context context) {
        this(context,null);
    }

    public MyBannerView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = View.inflate(context, R.layout.layout_customview_mybanner, this);
        /*获取控件*/
        custom_vp = view.findViewById(R.id.custom_vp);
        custom_ll = view.findViewById(R.id.custom_ll);

    }

    //设置adapter供调用
    public void setAdapter(PagerAdapter pagerAdapter){
        custom_vp.setAdapter(pagerAdapter);
        //ViewPager状态改变事件
        custom_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //当页面滑动的时候回调方法
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            //当松开的时候回调方法
            @Override
            public void onPageSelected(int position) {
                position = position%points.size();
                for (int i=0; i<points.size();i++){
                    if(position==i){
                        points.get(position).setSelected(true);
                    }else{
                        points.get(i).setSelected(false);
                    }
                }
            }
            //当状态改变时回调函数
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //开启自动轮播
    public void autoPlay(){
        myHandler.sendEmptyMessageDelayed(0,2000);
    }

    //停止自动轮播
    public void stopPlay(){
        myHandler.removeCallbacksAndMessages(null);
    }

    //实现Handmer
    public class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int item = custom_vp.getCurrentItem();
            item++;
            custom_vp.setCurrentItem(item);
            autoPlay();
        }
    }

    //    静态域实现内部类适配器
    public static class Custom_vpPagerAdapter extends PagerAdapter{
        private final Context context;


        public Custom_vpPagerAdapter(Context context,List<ImageView> list1) {
            this.context = context;
            list = list1;
            Log.d(TAG,"-------------"+list.size());
            for(int i=0;i<list.size();i++){
                //存放小圆点的视图控件
                ImageView point = new ImageView(context);
                //把判断好的小圆点放入控件中
                point.setImageResource(R.drawable.circle_selector);
                //设置两点之间的距离
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(10,0,10,0);
                point.setLayoutParams(params);
                //添加到points集合中
                points.add(point);
                custom_ll.addView(point);
            }
            //设置默认选中的状态
            points.get(0).setSelected(true);
        }

        //返回无限多的视图
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position = position%list.size();//防止内存溢出
            ImageView imageView = list.get(position);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
    }

四、使用此控件的小案例 (下面是在fragment中调用)当然不要忘记在布局中加载控件哦!

package com.bwei.lenovo.day11_myapp.fragment;

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.ImageView;

import com.bumptech.glide.Glide;
import com.bwei.lenovo.day11_myapp.R;
import com.bwei.lenovo.day11_myapp.bean.ShowYeBean;
import com.bwei.lenovo.day11_myapp.customView.MyBannerView;
import com.bwei.lenovo.day11_myapp.http.HttpConfig;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Home_fragment1 extends Fragment {

    private static final String TAG = "Home_fragment1------------";
    private List<ImageView> list;
    private MyBannerView myBannerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_home_fragment1, container, false);
        //找到自定义banner控件
        myBannerView = view.findViewById(R.id.myBannerView);
        //调用运行banner方法
        fragmentInitData();
        return view;
    }

    public void fragmentInitData() {
        //进行解析json
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(HttpConfig.banner_url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            //失败
            @Override
            public void onFailure(Call call, IOException e) {

            }
//            成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Gson gson = new Gson();
                ShowYeBean adBean = gson.fromJson(json, ShowYeBean.class);
                final List<ShowYeBean.DataBean> data = adBean.getData();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        list = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {
                            String icon = data.get(i).getIcon();
                            ImageView imageView = new ImageView(getActivity());
                            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            Glide.with(getActivity()).load(icon).into(imageView);
                            list.add(imageView);
                        }
                        //实现适配器
                        MyBannerView.Custom_vpPagerAdapter adapter = new MyBannerView.Custom_vpPagerAdapter(getActivity(), list);
                        myBannerView.setAdapter(adapter);
                        //开启轮播
                        myBannerView.autoPlay();
                    }
                });

            }
        });
    }


}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值