Android自定義View——ScrollChooseView 可以滑動選擇的View

圖紙

圖片.png
使用viewpager的效果圖
ScreenGif.gif
自定義View的效果圖
ScreenGif.gif

github地址

點(diǎn)擊這里

使用

compile 'com.github.superSp:ScrollChooseView:v1.0.2'
 String titles[] = new String[]{"早餐前", "早餐后", "午餐前", "午餐后", "晚餐前", "晚餐后", "睡前"};
 private int picIds[] = new int[]{
            R.mipmap.time_bg_breakfastbefore, R.mipmap.time_bg_breakfastafter,
            R.mipmap.time_bg_lunchbefore, R.mipmap.time_bg_lunchafter,
            R.mipmap.time_bg_dinnerbefor, R.mipmap.time_bg_dinnerafter,
            R.mipmap.time_bg_sleep
    };

 scrollChooseView.setTitles(titles);
 scrollChooseView.setPicIds(picIds);
 scrollChooseView.setOnScrollEndListener(new ScrollChooseView.OnScrollEndListener() {
            @Override
            public void currentPosition(int position) {
                Log.d(TAG, "當(dāng)前positin=" + position + " " + titles[position]);
            }
        });

實現(xiàn)方式

構(gòu)造方法


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

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

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

      textBound = new Rect();
      paint = new Paint();
      paint.setAntiAlias(true);
      paint.setColor(Color.WHITE);
      paint.setTextSize(DensityUtils.sp2px(getContext(), 10));

      mScroller = new Scroller(context);

  }
onMeasure

當(dāng)設(shè)置為wrap時候 高度顯示為200

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widhtMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        setMeasuredDimension(widhtMode == MeasureSpec.EXACTLY ? widthSize : widthSize, heightMode == MeasureSpec.EXACTLY ? heightSize : DensityUtils.dp2px(getContext(),100));
    }
    }

onDraw

繪制text并且根據(jù)當(dāng)前position切換背景和字體大小以及底部線

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (titles == null) {
            return;
        }
        drawText(canvas);
    }

    private void drawText(Canvas canvas) {
        for (int i = 0; i < titles.length; i++) {
            if (getCurrentPosition() == i) {
                paint.setTextSize(DensityUtils.sp2px(getContext(), 20));
                paint.getTextBounds(titles[i], 0, titles[i].length(), textBound);
                canvas.drawText(titles[i], getMeasuredWidth() / 6 * (2 * i + 1) - (textBound.width() / 2), (getMeasuredHeight() / 2) + textBound.height() / 2, paint);
                paint.setStrokeWidth(3);
                canvas.drawLine(getMeasuredWidth() / 6 * (2 * i + 1) - (textBound.width() / 2) - 10, (getMeasuredHeight() / 2) + textBound.height(),
                        getMeasuredWidth() / 6 * (2 * i + 1) + (textBound.width() / 2) + 10, (getMeasuredHeight() / 2) + textBound.height(), paint);

            } else {
                paint.setTextSize(DensityUtils.sp2px(getContext(), 10));
                paint.getTextBounds(titles[i], 0, titles[i].length(), textBound);
                canvas.drawText(titles[i], getMeasuredWidth() / 6 * (2 * i + 1) - (textBound.width() / 2), (getMeasuredHeight() / 2) + textBound.height() / 2, paint);
            }
            setBackgroundResource(picIds[getCurrentPosition()]);
        }
    }

getCurrentPosition() 獲取當(dāng)前所處的位置

這個等以后有時間完善吧宏榕。扎酷。目前item最多支持7個。剪撬。不過你想要支持更多稍坯,只要按照這個格式繼續(xù)添加就好了。。赐稽。

 //當(dāng)前的位置
    private int getCurrentPosition() {
        int position = 1;

        if (getScrollX() > getMeasuredWidth() / 6 * 1 * -3 && getScrollX() <= getMeasuredWidth() / 6 * 1 * -1) {
            position = 0;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * -1 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 1) {
            position = 1;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 1 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 3) {
            position = 2;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 3 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 5) {
            position = 3;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 5 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 7) {
            position = 4;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 7 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 9) {
            position = 5;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 9 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 11) {
            position = 6;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 11 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 13) {
            position = 7;
        } else if (getScrollX() > getMeasuredWidth() / 6 * 1 * 13 && getScrollX() <= getMeasuredWidth() / 6 * 1 * 15) {
            position = 8;
        }

        return position;

    }

onTouchEvent() 處理滑動

 @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (titles.length <= 1) {
            return super.onTouchEvent(event);
        }
        int x = (int) event.getX();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isClick = true;
                downX = x;
                break;
            case MotionEvent.ACTION_MOVE:
                isClick = false;
                int offset = x - downX;
                if (getScrollX() < -getMeasuredWidth() / 3 || getScrollX() > getMeasuredWidth() / 3 * titles.length - getMeasuredWidth() + getMeasuredWidth() / 3) {
                    return super.onTouchEvent(event);
                } else {
                    scrollX(lastScrollX - offset, true);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (isClick) {
                    return true;
                }
                if (getScrollX() < -getMeasuredWidth() / 3) {
                    scrollX(-getMeasuredWidth() / 3, true);
                }
                if (getScrollX() > getMeasuredWidth() / 3 * titles.length - getMeasuredWidth() + getMeasuredWidth() / 3) {
                    scrollX(getMeasuredWidth() / 3 * titles.length - getMeasuredWidth() + getMeasuredWidth() / 3, true);
                }

                scrollX(getMeasuredWidth() / 3 * (getCurrentPosition() - 1), false);

                break;
        }
        return true;
    }

接下來是Scroller自動滑動的普遍寫法。浑侥。

     /**
     * b 是代表手動滑 還是自動滑動姊舵。。
     *
     * @param endX
     * @param b
     */
    private void scrollX(int endX, boolean b) {
        if (b) {
            scrollTo(endX, 0);
        } else {
            isScroll = true;
            lastScrollX = endX;
            smoothScrollTo(endX, 0);
        }
    }

    public void smoothScrollTo(int destX, int destY) {
        // 第二步寓落,調(diào)用startScroll()方法來初始化滾動數(shù)據(jù)并刷新界面
        mScroller.startScroll(getScrollX(), 0, destX - getScrollX(), 0, 200);
        invalidate();
    }

    @Override
    public void computeScroll() {
        // 第三步括丁,重寫computeScroll()方法,并在其內(nèi)部完成平滑滾動的邏輯
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            invalidate();
        } else {
            if (isScroll) {
                setScrollX(lastScrollX);
                isScroll = false;
                if (onScrollEndListener != null) {
                    onScrollEndListener.currentPosition(getCurrentPosition());
                }
            }
        }
    }

供外部使用的接口和方法

設(shè)置標(biāo)題
 public void setTitles(String titles[]) {
        this.titles = titles;
        invalidate();
    }
設(shè)置背景圖片
public void setPicIds(int[] picIds) {
        this.picIds = picIds;
    }
設(shè)置滑動結(jié)束后的position監(jiān)聽
public void setOnScrollEndListener(OnScrollEndListener onScrollEndListener) {
        this.onScrollEndListener = onScrollEndListener;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末伶选,一起剝皮案震驚了整個濱河市史飞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌仰税,老刑警劉巖构资,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異陨簇,居然都是意外死亡吐绵,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進(jìn)店門河绽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拦赠,“玉大人,你說我怎么就攤上這事葵姥『墒螅” “怎么了?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵榔幸,是天一觀的道長允乐。 經(jīng)常有香客問我,道長削咆,這世上最難降的妖魔是什么牍疏? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮拨齐,結(jié)果婚禮上鳞陨,老公的妹妹穿的比我還像新娘。我一直安慰自己瞻惋,他們只是感情好厦滤,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布援岩。 她就那樣靜靜地躺著,像睡著了一般掏导。 火紅的嫁衣襯著肌膚如雪享怀。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天趟咆,我揣著相機(jī)與錄音添瓷,去河邊找鬼。 笑死值纱,一個胖子當(dāng)著我的面吹牛鳞贷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播虐唠,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼搀愧,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了凿滤?” 一聲冷哼從身側(cè)響起妈橄,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤庶近,失蹤者是張志新(化名)和其女友劉穎翁脆,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鼻种,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡反番,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了叉钥。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片罢缸。...
    茶點(diǎn)故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖投队,靈堂內(nèi)的尸體忽然破棺而出枫疆,到底是詐尸還是另有隱情,我是刑警寧澤敷鸦,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布息楔,位于F島的核電站,受9級特大地震影響扒披,放射性物質(zhì)發(fā)生泄漏值依。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一碟案、第九天 我趴在偏房一處隱蔽的房頂上張望愿险。 院中可真熱鬧,春花似錦价说、人聲如沸辆亏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽褒链。三九已至唁情,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間甫匹,已是汗流浹背甸鸟。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留兵迅,地道東北人抢韭。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像恍箭,于是被迫代替她去往敵國和親刻恭。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容