Android开发Android开发经验谈我爱编程

Android BannerView通用封装

2018-04-13  本文已影响166人  猪爸爸Hulk

之前封装过一个,但总觉得不够优雅,就有了这个通用封装,很简洁,不知道够不够优雅,不过原来那个有跟随指示器和丝滑滑动效果,感兴趣可以看一下。

封装过程

BannerView

1、自定义属性
selectPoint:选中指示器图标
normalPoint:未选中指示器图标
pointWidth:图标宽度
switchTime:轮播间隔事件
location:指示器位置,下中或下右

<declare-styleable name="NewBannerView">
        <attr name="selectPoint" format="reference" />
        <attr name="normalPoint" format="reference" />
        <attr name="pointWidth" format="dimension" />
        <attr name="switchTime" format="integer" />
        <attr name="location">
            <enum name="CENTER" value="0" />
            <enum name="RIGHT" value="1" />
        </attr>
    </declare-styleable>

2、初始化View
初始化ViewPager和指示器组合View
3、绑定数据源
通过setImageData设置轮播图数据源
4、绑定点击事件
通过OnPageClickListener绑定点击事件
5、开启关闭轮播
start和stop方法开启和关闭轮播

用法

xml中

<com.goldou.lovesee.view.NewBannerView
        android:id="@+id/bannerView"
        android:layout_width="match_parent"
        app:selectPoint="@drawable/red_point"
        app:normalPoint="@drawable/gray_point"
        app:switchTime="4000"
        app:location="RIGHT"
        android:layout_height="200dp" />

activity中

int[] imageList = {R.drawable.me_top, R.drawable.me_top, R.drawable.me_top, R.drawable.me_top};
        NewBannerView bannerView = view.findViewById(R.id.bannerView);
        bannerView.setImageData(imageList);
        bannerView.start();
        bannerView.setOnPageClickListener(new NewBannerView.OnPageClickListener() {
            @Override
            public void onPageClick(int position) {
                Toast.makeText(getActivity(), position + "", Toast.LENGTH_SHORT).show();
            }
        });

BannerView

public class NewBannerView extends RelativeLayout implements View.OnClickListener {
    private Context context;
    private int selectPoint, normalPoint;
    private float pointWidth = 7;
    private int location;
    private int CENTER = 0, RIGHT = 1;
    private int lastPosition = 0;
    private ViewPager viewPager;
    private int switchTime = 5000;
    private int[] images;
    private OnPageClickListener onPageClickListener;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 101) {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                start();
            }
            return false;
        }
    });

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

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

    public NewBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initAttr(attrs);
    }

    private void initAttr(AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.NewBannerView);
        selectPoint = array.getResourceId(R.styleable.NewBannerView_selectPoint, R.mipmap.ic_launcher_round);
        normalPoint = array.getResourceId(R.styleable.NewBannerView_normalPoint, R.mipmap.ic_launcher_round);
        pointWidth = array.getDimension(R.styleable.NewBannerView_pointWidth, pointWidth);
        location = array.getInteger(R.styleable.NewBannerView_location, RIGHT);
        switchTime = array.getInteger(R.styleable.NewBannerView_switchTime, switchTime);
        array.recycle();
    }

    public void setImageData(final int[] images) {
        this.images = images;
        final LinearLayout ll_point = new LinearLayout(context);
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        layoutParams.bottomMargin = 20;
        if (location == CENTER) {
            layoutParams.addRule(CENTER_HORIZONTAL, RelativeLayout.TRUE);
        } else {
            layoutParams.addRule(ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
            layoutParams.rightMargin = 20;
        }
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(UIUtil.dip2px(pointWidth), UIUtil.dip2px(pointWidth));
        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(UIUtil.dip2px(pointWidth), UIUtil.dip2px(pointWidth));
        params1.leftMargin = 0;
        params2.leftMargin = UIUtil.dip2px(pointWidth);
        for (int i = 0; i < images.length; i++) {
            ImageView point = new ImageView(context);
            if (i == 0) {
                point.setBackgroundResource(selectPoint);
                point.setLayoutParams(params1);
            } else {
                point.setBackgroundResource(normalPoint);
                point.setLayoutParams(params2);
            }
            ll_point.addView(point);
        }

        viewPager = new ViewPager(context);
        viewPager.setAdapter(new BannerAdapter());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                position = position % images.length;
                if (lastPosition == position) {
                    return;
                }
                ll_point.getChildAt(position).setBackgroundResource(selectPoint);
                ll_point.getChildAt(lastPosition).setBackgroundResource(normalPoint);
                lastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        LayoutParams layoutParams1 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        addView(viewPager, layoutParams1);
        addView(ll_point, layoutParams);
    }

    public void start() {
        handler.sendEmptyMessageDelayed(101, switchTime);
    }

    public void stop() {
        handler.removeCallbacksAndMessages(null);
    }

    private int getCurrentItem() {
        return viewPager.getCurrentItem() % images.length;
    }

    @Override
    public void onClick(View view) {
        onPageClickListener.onPageClick(getCurrentItem());
    }

    public interface OnPageClickListener {
        void onPageClick(int position);
    }

    public void setOnPageClickListener(OnPageClickListener onPageClickListener) {
        this.onPageClickListener = onPageClickListener;
    }

    private class BannerAdapter extends PagerAdapter {

        @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 % images.length;
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(images[position]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setOnClickListener(NewBannerView.this);
            container.addView(imageView);
            return imageView;
        }

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

上一篇下一篇

猜你喜欢

热点阅读