为了账号安全,请及时绑定邮箱和手机立即绑定

可以伸缩的搜索栏,模仿华为应用市场

标签:
Html5

本项目的 GitHub 地址:https://github.com/yuqirong/FlexibleSearchBar

关于搜索栏,可以说各种 app 都有不同的样式。影响比较深刻的就有华为应用市场的搜索栏(同样,简书的搜索栏也是类似的)。

而今天,就是带你来实现华为应用市场那样的搜索栏。

我们先放上我们实现的效果图吧:

demo效果图

怎么样,想不想学?

我们先来简述一下实现的思路吧,其实并不复杂。

首先,在搜索栏还未打开时,先确定半径 R ,然后假设一个变量 offset 用来动态改变搜索栏的宽度。如图所示:

示意图

所以可以得到一个公式:offset = total width - 2 * R ;

那么显而易见,offset 的取值就在 [0, total width - 2 * R] 之间了。

所以,我们可以借助属性动画来完成这数值的变化。在调用 invalidate() 进行重绘,达到动态增加搜索栏宽度的效果。反之,关闭搜索栏也是同理的。

那么下面就用代码来实现它咯!

attrs

关于自定义的属性,我们可以想到的有搜索栏的背景颜色、搜索栏的位置(左或右)、搜索栏的状态(打开或关闭)等。具体的可以查看下面的 attrs.xml 。根据英文应该能知道对应属性的作用了。

<?xml version="1.0" encoding="utf-8"?><resources>
    <declare-styleable name="SearchBarView">
        <attr name="search_bar_color" format="color|reference" />
        <attr name="search_bar_position" format="enum">
            <enum name="position_left" value="4" />
            <enum name="position_right" value="1" />
        </attr>
        <attr name="search_bar_status" format="enum">
            <enum name="status_close" value="4" />
            <enum name="status_open" value="1" />
        </attr>
        <attr name="search_bar_duration" format="integer" />
        <attr name="search_bar_hint_text" format="string|reference" />
        <attr name="search_bar_icon" format="reference" />
        <attr name="search_bar_hint_text_color" format="color|reference" />
        <attr name="search_bar_hint_text_size" format="dimension|reference" />
    </declare-styleable></resources>

constructor

而在构造器中,肯定就是初始化一些 attrs 中的全局变量了,这也不是重点,都是机械式的代码。

public SearchBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SearchBarView);
    searchBarColor = array.getColor(R.styleable.SearchBarView_search_bar_color, DEFAULT_SEARCH_BAR_COLOR);
    mPosition = array.getInteger(R.styleable.SearchBarView_search_bar_position, DEFAULT_RIGHT_POSITION);
    mStatus = array.getInteger(R.styleable.SearchBarView_search_bar_status, STATUS_CLOSE);    int mDuration = array.getInteger(R.styleable.SearchBarView_search_bar_duration, DEFAULT_ANIMATION_DURATION);    int searchBarIcon = array.getResourceId(R.styleable.SearchBarView_search_bar_icon, android.R.drawable.ic_search_category_default);
    mSearchText = array.getText(R.styleable.SearchBarView_search_bar_hint_text);
    searchTextColor = array.getColor(R.styleable.SearchBarView_search_bar_hint_text_color, DEFAULT_SEARCH_TEXT_COLOR);    float defaultTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_HINT_TEXT_SIZE, getResources().getDisplayMetrics());    float searchTextSize = array.getDimension(R.styleable.SearchBarView_search_bar_hint_text_size, defaultTextSize);
    defaultHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_HEIGHT, getResources().getDisplayMetrics());
    array.recycle();
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setColor(searchBarColor);
    mPaint.setTextSize(searchTextSize);
    mRectF = new RectF();
    mDstRectF = new RectF();
    bitmap = BitmapFactory.decodeResource(getResources(), searchBarIcon);
    initAnimator(mDuration);
}

initAnimator

initAnimator 方法中是两个属性动画,打开和关闭动画。非常 easy 的代码。

private void initAnimator(long duration) {
    AccelerateInterpolator accelerateInterpolator = new AccelerateInterpolator();
    ValueAnimator.AnimatorUpdateListener animatorUpdateListener = new ValueAnimator.AnimatorUpdateListener() {        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mOffsetX = (int) animation.getAnimatedValue();
            invalidate();
        }
    };    // init open animator
    openAnimator = new ValueAnimator();
    openAnimator.setInterpolator(accelerateInterpolator);
    openAnimator.setDuration(duration);
    openAnimator.addUpdateListener(animatorUpdateListener);
    openAnimator.addListener(new AnimatorListenerAdapter() {        @Override
        public void onAnimationStart(Animator animation) {
            mStatus = STATUS_PROCESS;
        }        @Override
        public void onAnimationEnd(Animator animation) {
            mStatus = STATUS_OPEN;
            invalidate();
        }
    });    // init close animator
    closeAnimator = new ValueAnimator();
    openAnimator.setInterpolator(accelerateInterpolator);
    closeAnimator.setDuration(duration);
    closeAnimator.addUpdateListener(animatorUpdateListener);
    closeAnimator.addListener(new AnimatorListenerAdapter() {        @Override
        public void onAnimationStart(Animator animation) {
            mStatus = STATUS_PROCESS;
        }        @Override
        public void onAnimationEnd(Animator animation) {
            mStatus = STATUS_CLOSE;
        }
    });
}

onMeasure

同样,onMeasure 中的代码也是很机械的,基本上都是同一个套路了。

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    int widthMode = MeasureSpec.getMode(widthMeasureSpec);    int widthSize = MeasureSpec.getSize(widthMeasureSpec);    int heightMode = MeasureSpec.getMode(heightMeasureSpec);    int heightSize = MeasureSpec.getSize(heightMeasureSpec);    if (widthMode == MeasureSpec.EXACTLY) {
        mWidth = widthSize;
    } else {
        mWidth = widthSize;
    }    if (heightMode == MeasureSpec.EXACTLY) {
        mHeight = heightSize;
    } else {
        mHeight = (int) defaultHeight;        if (heightMode == MeasureSpec.AT_MOST) {
            mHeight = Math.min(heightSize, mHeight);
        }
    }    // 搜索栏小圆圈的半径
    mRadius = Math.min(mWidth, mHeight) / 2;    if (mStatus == STATUS_OPEN) {
        mOffsetX = mWidth - mRadius * 2;
    }
    setMeasuredDimension(mWidth, mHeight);
}

onDraw

onDraw 中先画了搜索栏的背景,然后是搜索栏的图标,最后是搜索栏的提示文字。

画背景的时候,是需要根据搜索栏在左边还是右边的位置来确定值的。

而画图标的时候,是根据搜索栏关闭时那个圆的内切正方形作为 Rect 的。

最后画提示文字没什么好讲的了,都是定死的代码。

@Overrideprotected void onDraw(Canvas canvas) {    // draw search bar
    mPaint.setColor(searchBarColor);    int left = mPosition == DEFAULT_RIGHT_POSITION ? mWidth - 2 * mRadius - mOffsetX : 0;    int right = mPosition == DEFAULT_RIGHT_POSITION ? mWidth : 2 * mRadius + mOffsetX;    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        canvas.drawRoundRect(left, 0, right, mHeight, mRadius, mRadius, mPaint);
    } else {
        mRectF.set(left, 0, right, mHeight);
        canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
    }    // draw search bar icon
    mDstRectF.set(left + (int) ((1 - Math.sqrt(2) / 2) * mRadius), (int) ((1 - Math.sqrt(2) / 2) * mRadius),
            left + (int) ((1 + Math.sqrt(2) / 2) * mRadius), (int) ((1 + Math.sqrt(2) / 2) * mRadius));
    canvas.drawBitmap(bitmap, null, mDstRectF, mPaint);    // draw search bar text
    if (mStatus == STATUS_OPEN && !TextUtils.isEmpty(mSearchText)) {
        mPaint.setColor(searchTextColor);
        Paint.FontMetrics fm = mPaint.getFontMetrics();        double textHeight = Math.ceil(fm.descent - fm.ascent);
        canvas.drawText(mSearchText.toString(), 2 * mRadius, (float) (mRadius + textHeight / 2 - fm.descent), mPaint);
    }
}

startOpen、startClose

最后,需要将 startOpenstartClose 方法暴露给外部,方便调用。在其内部就是调用两个属性动画而已。

/**
 * 判断搜索栏是否为打开状态
 *
 * @return
 */public boolean isOpen() {    return mStatus == STATUS_OPEN;
}/**
 * 判断搜索栏是否为关闭状态
 *
 * @return
 */public boolean isClose() {    return mStatus == STATUS_CLOSE;
}/**
 * 打开搜索栏
 */public void startOpen() {    if (isOpen()) {        return;
    } else if (openAnimator.isStarted()) {        return;
    } else if (closeAnimator.isStarted()) {
        closeAnimator.cancel();
    }
    openAnimator.setIntValues(mOffsetX, mWidth - mRadius * 2);
    openAnimator.start();
}/**
 * 关闭搜索栏
 */public void startClose() {    if (isClose()) {        return;
    } else if (closeAnimator.isStarted()) {        return;
    } else if (openAnimator.isStarted()) {
        openAnimator.cancel();
    }
    closeAnimator.setIntValues(mOffsetX, 0);
    closeAnimator.start();
}

End

到这也差不多了,该讲的都讲了,这篇写得真 TMD 简洁。至于和 AppBarLayout 的混合使用,见 GitHub 中的代码即可。



作者:俞其荣
链接:https://www.jianshu.com/p/c6cfd88dbe2d


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消