自定义View轮播图

1.     运用自定义组合控件实现轮播图效果,必须自定义实现;

2.     调用如下接口地址,解析轮播图数据,展示到页面上;

3.     实现自动轮播和手动滑动切换;

4.     页面底部指示器小圆点的绘制。

5.     按type类型判断,如果type为0则跳转到详情页(详情页返回字段:url),如果type为1则toast提示“我要跳转到商品详情页”


XML   layout文件 


main布局

<com.bwei.duanpeng20180102_01.CustomBanner
    android:id="@+id/custom_banner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
com.bwei.duanpeng20180102_01.CustomBanner>

web布局
 
  
<WebView
    android:id="@+id/web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
WebView>
 
  
custom_banner_layout布局
<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    >
android.support.v4.view.ViewPager>
<LinearLayout
    android:id="@+id/linear_layout"
    android:orientation="horizontal"
    android:layout_alignBottom="@+id/view_pager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
LinearLayout>
 
  
XML drawable布局文件

shape_01布局
 
  
xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#00ff00"/>

    <corners android:radius="10dp"/>

    <size android:height="10dp" android:width="10dp"/>

shape>
shape_02布局
 
  
xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

<solid android:color="#ff0000"/>

<corners android:radius="10dp"/>

<size android:height="10dp" android:width="10dp"/>

shape>
 
  

Java代码

MainActivity方法
public class MainActivity extends AppCompatActivity {
    private int time = 100;
    private CustomBanner customBanner;
    private List list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        customBanner = (CustomBanner) findViewById(R.id.custom_banner);
        customBanner.setTimeSeconds(3);
        getDataFromNet();
    }

    private void getDataFromNet() {
        //http://120.27.23.105/ad/getAd
        //1.创建一个okhttp客户端对象
        OkHttpClient httpClient=new OkHttpClient();
        //2.通过请求的构建器来创建一个请求对象,并指定请求的url地址
        Request request = new Request.Builder()
                .url("http://120.27.23.105/ad/getAd")
                .build();
        okhttp3.Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    final String string = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("---+++",string);
                            BannerBean bannerBean = new Gson().fromJson(string, BannerBean.class);
                            final List data = bannerBean.getData();

                            list = new ArrayList<>();
                            for (int i = 0;ilist.add(data.get(i).getIcon());
                            }
                            customBanner.setImageUrl(list);
                            //设置点击事件
                            customBanner.setOnBannerClickListner(new CustomBanner.OnBannerClickListner() {
                                @Override
                                public void onBannerClick(int position) {
                                    //Toast.makeText(MainActivity.this,"点击了",Toast.LENGTH_SHORT).show();
                                    //判断
                                    BannerBean.DataBean dataBean = data.get(position);
                                    if (dataBean.getType() == 0){//跳转到详情
                                        Intent intent = new Intent(MainActivity.this,WebActivity.class);
                                        intent.putExtra("url",dataBean.getUrl());
                                        startActivity(intent);

                                    }else if (dataBean.getType() == 1){
                                        Toast.makeText(MainActivity.this,"我要跳转到商品详情页",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    }

}

WebActivity方法
 
  
public class WebActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        WebView webView = (WebView) findViewById(R.id.web_view);

        Intent intent = getIntent();
        String url = intent.getStringExtra("url");

        //加载
        webView.loadUrl(url);

        //设置
        webView.setWebViewClient(new WebViewClient());

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
    }
}
CustomBanner方法
 
  
public class CustomBanner extends FrameLayout {
    private ViewPager viewPager;
    private LinearLayout linearLayout;
    private List list;

    private int time = 2;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                //viewPager显示下一页
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);

                //再次发送延时消息
                handler.sendEmptyMessageDelayed(0, time * 1000);
            }
        }
    };

    private ArrayList images;
    private OnBannerClickListner bannerClickListner;

    public CustomBanner(@NonNull Context context) {
        super(context);
        init();
    }

    public CustomBanner(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 对外提供设置时间
     */
    public void setTimeSeconds(int time) {
        this.time = time;
    }

    /**
     * 初始化的方法,,,加载布局
     */
    private void init() {

        View view = View.inflate(getContext(), R.layout.custom_banner_layout, this);
        //找到控件
        viewPager = (ViewPager) view.findViewById(R.id.view_pager);
        linearLayout = (LinearLayout) view.findViewById(R.id.linear_layout);


    }

    /**
     * 对外提供设置数据的方法
     */
    public void setImageUrl(List list) {
        this.list = list;

        if (list == null) {
            return;
        }

        //设置适配器
        MyAdapter myAdapter = new MyAdapter(getContext(), list);

        //设置适配器
        viewPager.setAdapter(myAdapter);

        initDoc(list);

        //2.手动的可以无限滑动
        viewPager.setCurrentItem(list.size() * 100000);//设置当前展示中间某个足够大的位置

        handler.sendEmptyMessageDelayed(0, time * 1000);//发送一个延时的空消息

        //viewPage设置监听事件
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            /**
             * 当选中某个页面的时候,把当前的小圆点背景变成绿色
             * @param position
             */
            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < images.size(); i++) {
                    if (i == position % images.size()) {

                        images.get(i).setImageResource(R.drawable.shape_01);
                    } else {
                        images.get(i).setImageResource(R.drawable.shape_02);
                    }

                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
    /**
     * 动态添加小圆点
     *
     * @param list
     */
    private void initDoc(List list) {
        //1.需要一个集合记录一下小圆点的imageView控件
        images = new ArrayList();
        //2...linearLayout上面的视图清空一下再去添加
        linearLayout.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            if (i == 0) {
                imageView.setImageResource(R.drawable.shape_01);
            } else {
                imageView.setImageResource(R.drawable.shape_02);
            }
            //添加到集合去
            images.add(imageView);
            //添加到线性布局上
            //这是布局参数,,刚开始小圆点之间没有距离,所以使用java代码指定宽度高度,并且指定小圆点之间的距离
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 0, 5, 0);
            linearLayout.addView(imageView, params);
        }
    }
    private class MyAdapter extends PagerAdapter {
        Context context;
        List list;

        public MyAdapter(Context context, List list) {
            this.context = context;
            this.list = list;
        }
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
        /**
         * viewPager具有预加载,默认的前后加载一页,,,默认的容器里面最多三页
         *
         * @param container
         * @param position
         * @return
         */
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            //1.把这个当前展示的视图添加到容器中...container
            ImageView imageView = new ImageView(context);
            //..........使图片平铺整个imageView控件
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            //imageLoader加载图片到这个imageView控件上
            Glide.with(context).load(list.get(position%list.size())).into(imageView);
            //给imageView设置触摸的监听事件
            imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int action = motionEvent.getAction();//获取手指的动作
                    switch (action) {
                        case MotionEvent.ACTION_DOWN://按下的动作...应该取消发送消息的操作
                            handler.removeCallbacksAndMessages(null);

                            break;
                        case MotionEvent.ACTION_MOVE://移动的动作
                            handler.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_CANCEL://取消
                            //重新发送
                            handler.sendEmptyMessageDelayed(0, time * 1000);
                            break;
                        case MotionEvent.ACTION_UP://抬起的动作
                            handler.sendEmptyMessageDelayed(0, time * 1000);
                            break;
                    }
                    return false;
                }
            });
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    bannerClickListner.onBannerClick(position % list.size());
                }
            });
            container.addView(imageView);//添加到容器
            //2.把当前展示的视图返回
            return imageView;
        }

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

    public void setOnBannerClickListner(OnBannerClickListner bannerClickListner){
        this.bannerClickListner = bannerClickListner;
    }

    /**
     * 点击的接口
     */
    public interface OnBannerClickListner {
        public void onBannerClick(int position);
    }
}
BannerBear 接口

 
  
http://120.27.23.105/ad/getAd

build里面引用方法
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'

 
  
权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
  

你可能感兴趣的:(自定义View轮播图)