Android-自定义viewAndroid进阶Android开发经验谈

Android自定义View--Flyme6的Viewpage

2017-09-16  本文已影响105人  生椰拿铁锤

最新更新的Flyme6整体效果不错,动画效果增加了很多了,看了看flyme6的Viewpager指示器,觉得有点意思,就模仿写了一下,整体效果如下:


效果演示图

github地址:https://github.com/Dawish/FlymeTabStrip

Gradle

滑动绘制原理示意图

onDraw主要的绘制工作:

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 如果指示器个数为0,直接结束绘画
        if (tabCount == 0) {
            return;
        }
        // 获取onMeasure后的高
        final int height = getHeight();
        /*
         * 画指示器下方的线
         */
        // 设置颜色
        paint.setColor(indicatorColor);
        // 当前指示tab位置
        View currentTab = container.getChildAt(currentPosition);
        // 当前tab的左边相对父容器的左边距
        float leftPadding = currentTab.getLeft();
        // 当前tab的右边相对于父容器左边距
        float rightPadding = currentTab.getRight();
        float tempPadding = 20;
        // 如果出现位移

        float centerPosition = 0.0f;

        if (currentPositionOffset >= 0f && currentPosition < tabCount - 1) {
            View nextTab = container.getChildAt(currentPosition + 1);
            final float nextTabLeft = nextTab.getLeft();
            final float nextTabRight = nextTab.getRight();
            // 位置是在滑动过程中不断变化的
            leftPadding = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * leftPadding);
            rightPadding = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * rightPadding);
        }
        centerPosition = (rightPadding - leftPadding)/2 + leftPadding;
        float left = centerPosition - tempPadding - formatPercent(currentPositionOffset)*tempPadding;
        float right = centerPosition + tempPadding + formatPercent(currentPositionOffset)*tempPadding;

        // 绘制
        canvas.drawRect(left, height - indicatorHeight, right, height, paint);

    }

上一篇下一篇

猜你喜欢

热点阅读