Android——自定义view实现轮播图

1.添加依赖
implementation ‘com.squareup.okio:okio:1.5.0’
implementation ‘com.squareup.okhttp3:okhttp:3.2.0’
implementation ‘com.github.bumptech.glide:glide:4.9.0’
implementation ‘com.squareup.okhttp3:logging-interceptor:3.4.1’

添加权限

2.封装单例OkHttp

public class OkHttpUtils {
    //私有的静态的成员变量,只声明不创建
    private static OkHttpUtils okHttpUtils = null;
    //私有的构造方法

    private OkHttpUtils() {

    }

    //返回公共静态的实例方法
    public static OkHttpUtils getInstance() {
        if (okHttpUtils == null) {
            synchronized (OkHttpUtils.class) {

                if (okHttpUtils == null) {
                    okHttpUtils = new OkHttpUtils();
                }
            }
        }


        return okHttpUtils;
    }

    private static OkHttpClient okHttpClient = null;

    //返回ok
    public synchronized static OkHttpClient getOkHttpClient() {

        if (okHttpClient == null) {
            //创建日志拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.i("xxx", message);
                }
            });
            //设置日志拦截器模式
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //创建okHttpClient

            okHttpClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
        }


        return okHttpClient;


    }

    //get请求
    public void doGet(String url, Callback callback) {
        //创建OkHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        //创建Request
        Request request = new Request.Builder().url(url).build();

        Call call = okHttpClient.newCall(request);
        //执行异步
        call.enqueue(callback);


    }
    //post请求
    public void doPost(String url, Map parmars, Callback callback) {
        //创建OkHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        //创建builder
        FormBody.Builder builder = new FormBody.Builder();
        //遍历集合
        for (String key : parmars.keySet()) {
            builder.add(key,parmars.get(key));

        }

        //构建FormBody
        FormBody formBody = builder.build();

        //创建Request
        Request request = new Request.Builder().url(url).post(formBody).build();

        Call call = okHttpClient.newCall(request);
        //执行异步
        call.enqueue(callback);


    }
}

3.创建自定义view实现轮播
布局




    

    


public class CustomViewGroup extends RelativeLayout {

    private ViewPager vp;
    private LinearLayout ll_point;
    private List imageViews=new ArrayList<>();
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String json= (String) msg.obj;
                    try {
                        JSONObject jsonObject=new JSONObject(json);
                        JSONArray result = jsonObject.getJSONArray("result");
                        for (int i = 0; i < result.length(); i++){
                            JSONObject jo = result.getJSONObject(i);
                            String imageUrl = jo.getString("imageUrl");
                            ImageView imageView=new ImageView(getContext());
                            Glide.with(getContext()).load(imageUrl).into(imageView);
                            imageViews.add(imageView);
                        }
                        MyViewPagerAdapter adapter=new MyViewPagerAdapter();
                        vp.setAdapter(adapter);

                        initPoint(imageViews);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

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

    public CustomViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView(context);
    }

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

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.custom_viewpager, null, false);
        addView(view);

        vp = view.findViewById(R.id.vp);
        ll_point = view.findViewById(R.id.ll_point);

        getBannerData();
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                position %= imageViews.size();
                //获取小圆点个数
                int count = ll_point.getChildCount();
                for (int i = 0; i < count; i++) {

                    View view = ll_point.getChildAt(i);
                    //设置选中状态
                    view.setEnabled(i == position ? false : true);

                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void getBannerData() {
        OkHttpUtils.getInstance().doGet("http://172.17.8.100/small/commodity/v1/bannerShow", 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();
                Message message=new Message();
                message.what=0;
                message.obj=json;
                handler.sendMessage(message);
            }
        });
    }

    //轮播适配器
    private class MyViewPagerAdapter extends PagerAdapter {
        //返回Integer长度 不断循环
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

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

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            position %= imageViews.size();

            ImageView imageView = imageViews.get(position);
            container.addView(imageView);

            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

            container.removeView((View) object);
        }
    }

    //添加小圆点
    private void initPoint(List imageViews) {

        for (int i = 0; i < imageViews.size(); i++) {
            //创建小圆点
            View view = new View(getContext());
            view.setBackgroundResource(R.drawable.point_bg_selector);
            //自定义大小
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.rightMargin = 20;
            //把小圆点动态添加到布局中
            ll_point.addView(view, params);


        }

        View view = ll_point.getChildAt(0);
        //默认第一个选中的
        view.setEnabled(false);
    }

    //开始轮播
    public void startBanner() {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                int currentItem = vp.getCurrentItem();
                currentItem++;
                vp.setCurrentItem(currentItem);

                handler.postDelayed(this, 2000);
            }
        }, 2000);


    }


    //停止轮播
    public void stopBanner() {

        handler.removeCallbacksAndMessages(null);
    }

    //测量
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

    //摆放
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }
}

4.主页面调用



public class MainActivity extends AppCompatActivity {

    private CustomViewGroup customViewGroup;

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

        customViewGroup = findViewById(R.id.cvg);
    }

    @Override
    protected void onResume() {
        super.onResume();
        customViewGroup.startBanner();
    }

    @Override
    protected void onPause() {
        super.onPause();
        customViewGroup.stopBanner();
    }
}

你可能感兴趣的:(资讯)