Android中Banner的指示器自定義View

Banner是我們經(jīng)常會遇到的一個功能,有很多是需要支持滑動是有個當(dāng)前的指示器界面,一般如果為了圖省事的方案可以用LinearLayout然后不斷的在里面添加View,把背景通過shape來設(shè)置圓形。這種做法雖然比較簡單,但是用到的控件太多,對性能并不好。為了解決這個問題通過對需求的思考,用自定義的View來做就很容易了。下面是我的寫的這個View,你可以直接復(fù)制粘貼到代碼中;

代碼如下:

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;


/***
 *@date 創(chuàng)建時間 2018/3/3
 *@author 作者: 壹樹
 *@description  Banner的當(dāng)前索引指示器自定義View
 */
public class BannerIndicatorView extends View {
    public static final int INDICATOR_STYLE_CIRCLE = 0;
    public static final int INDICATOR_STYLE_RECT = 1;

    /*** 指示器中的總數(shù)**/
    private int cellCount = 0;
    /*** 當(dāng)前選中的位置**/
    private int currentPosition;
    /*** 小點之間的間距*/
    private int cellMarginSize = 10;
    /*** 指示器元素的半徑(注意是半徑,不是直徑)**/
    private int cellRadius = 10;
    /****未選中的顏色*/
    private int normalColor;
    /*** 選中的顏色**/
    private int selectedColor;
    /*** 小點的樣式,默認(rèn)是圓形*/
    private int indicatorStyle = INDICATOR_STYLE_CIRCLE;

    private Paint paint;

    public BannerIndicatorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setAntiAlias(true);
        initAttrs(context, attrs);
    }

    private void initAttrs(Context context, @Nullable AttributeSet attrs) {
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.BannerIndicatorView);
        cellCount = t.getInt(R.styleable.BannerIndicatorView_app_cell_count, 0);
        currentPosition = t.getInt(R.styleable.BannerIndicatorView_app_current_position, 0);
        indicatorStyle = t.getInt(R.styleable.BannerIndicatorView_app_indicator_style, INDICATOR_STYLE_CIRCLE);

        cellRadius = t.getDimensionPixelOffset(R.styleable.BannerIndicatorView_app_cell_radius, 10);
        cellMarginSize = t.getDimensionPixelOffset(R.styleable.BannerIndicatorView_app_cell_margin, 10);

        normalColor = t.getColor(R.styleable.BannerIndicatorView_app_normal_color, Color.WHITE);
        selectedColor = t.getColor(R.styleable.BannerIndicatorView_app_selected_color, 0xfff0f0f0);
        t.recycle();
    }

    public int getCellCount() {
        return cellCount;
    }

    /***
     * 設(shè)置當(dāng)前所要顯示的總數(shù)
     * @param cellCount
     */
    public void setCellCount(int cellCount) {
        this.cellCount = cellCount;
        invalidate();
    }

    /**
     * 返回當(dāng)前的位置
     * @return
     */
    public int getCurrentPosition() {
        return currentPosition;
    }

    /***
     * 設(shè)置當(dāng)前選中的位置
     * @param currentPosition
     */
    public void setCurrentPosition(int currentPosition) {
        this.currentPosition = currentPosition;
        invalidate();
    }

    /***
     * 和ViewPager綁定,這樣可以和ViewPager進行聯(lián)動了
     * @param viewPager 需要綁定的ViewPager
     * @param count 傳入ViewPager中實際的Item個數(shù)
     */
    public void bindWithViewPager(ViewPager viewPager, int count){
        cellCount = count;
        if (viewPager != null){
            currentPosition = viewPager.getCurrentItem();
            viewPager.addOnPageChangeListener(onPageChangeListener);
        }
    }

    /***和綁定ViewPager,這樣可以和ViewPager進行聯(lián)動了*/
    public void bindWithViewPager(ViewPager viewPager){
        if (viewPager != null){
            cellCount = viewPager.getAdapter().getCount();
            currentPosition = viewPager.getCurrentItem();
            viewPager.addOnPageChangeListener(onPageChangeListener);
        }
    }

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            if (cellCount > 0){
                setCurrentPosition(position % cellCount);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawCells(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 重新測量當(dāng)前界面的寬度
        int width = getPaddingLeft() + getPaddingRight() + cellRadius * 2 * cellCount + cellMarginSize * (cellCount - 1);
        int height = getPaddingTop() + getPaddingBottom() + cellRadius * 2;
        width = resolveSize(width, widthMeasureSpec);
        height = resolveSize(height, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    /**繪制當(dāng)前的指示器*/
    private void drawCells(Canvas canvas) {
        for (int i = 0; i < cellCount; i++) {
            if (i == currentPosition) {
                paint.setColor(selectedColor);
            } else {
                paint.setColor(normalColor);
            }
            int left = getPaddingLeft() + i * cellRadius * 2 + cellMarginSize * i;

            if (indicatorStyle == INDICATOR_STYLE_CIRCLE) {
                canvas.drawCircle(left + cellRadius, getHeight() / 2, cellRadius, paint);
            } else if (indicatorStyle == INDICATOR_STYLE_RECT) {
                Rect rect = new Rect();
                rect.left = left;
                rect.right = left + cellRadius * 2;
                rect.top = getPaddingTop();
                rect.bottom = rect.top + cellRadius * 2;
                canvas.drawRect(rect, paint);
            }
        }
    }
}

然后在 attr.xml文件中定義attr屬性

  <declare-styleable name="IndicatorView">
    <attr name="app_cell_radius" format="dimension"></attr>
    <attr name="app_cell_margin" format="dimension"></attr>
    <attr name="app_cell_count" format="integer"></attr>
    <attr name="app_current_position" format="integer"></attr>
    <attr name="app_selected_color" format="color|reference"></attr>
    <attr name="app_normal_color" format="color|reference"></attr>
    <attr name="app_indicator_style" format="enum">
        <enum name="CIRCLE" value="0"></enum>
        <enum name="RECT" value="1"></enum>
    </attr>
</declare-styleable>

編譯,最后就可以直接使用了。使用方法如下:

     <com.aquila.ui.practice.IndicatorView
        xmlns:app="http://schemas.android.com/apk/res-auto"

        android:id="@+id/indicator_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="#20f0"

        app:app_cell_count="8"
        app:app_current_position="2"
        app:app_cell_radius="8dp"
        app:app_cell_margin="10dp"
        app:app_normal_color="#f00"
        app:app_selected_color="#00f"
        app:app_indicator_style="CIRCLE"
        />

最后附上效果圖:


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容