前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >可以伸缩的搜索栏,模仿华为应用市场

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

作者头像
俞其荣
发布2022-07-28 08:24:05
5280
发布2022-07-28 08:24:05
举报
文章被收录于专栏:俞其荣的博客

本项目的 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 。根据英文应该能知道对应属性的作用了。

代码语言:javascript
复制
<?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 中的全局变量了,这也不是重点,都是机械式的代码。

代码语言:javascript
复制
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 的代码。

代码语言:javascript
复制
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 中的代码也是很机械的,基本上都是同一个套路了。

代码语言:javascript
复制
@Override
protected 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 的。

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

代码语言:javascript
复制
@Override
protected 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 方法暴露给外部,方便调用。在其内部就是调用两个属性动画而已。

代码语言:javascript
复制
/**
 * 判断搜索栏是否为打开状态
 *
 * @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 中的代码即可。

有问题的可以在下面留言。没问题的老铁可以来一波 star 。

FlexibleSearchBar:https://github.com/yuqirong/FlexibleSearchBar

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-12-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • attrs
  • constructor
  • initAnimator
  • onMeasure
  • onDraw
  • startOpen、startClose
  • End
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档