Android仿华为应用市场伸缩的搜索栏
关于搜索栏,可以说各种 app 都有不同的样式。影响比较深刻的就有华为应用市场的搜索栏(同样,简书的搜索栏也是类似的)。
而今天,就是带你来实现华为应用市场那样的搜索栏。
我们先放上我们实现的效果图吧:

怎么样,想不想学?
我们先来简述一下实现的思路吧,其实并不复杂。
首先,在搜索栏还未打开时,先确定半径 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() {@Overridepublic void onAnimationUpdate(ValueAnimator animation) {mOffsetX = (int) animation.getAnimatedValue();invalidate();}};// init open animatoropenAnimator = new ValueAnimator();openAnimator.setInterpolator(accelerateInterpolator);openAnimator.setDuration(duration);openAnimator.addUpdateListener(animatorUpdateListener);openAnimator.addListener(new AnimatorListenerAdapter() {@Overridepublic void onAnimationStart(Animator animation) {mStatus = STATUS_PROCESS;}@Overridepublic void onAnimationEnd(Animator animation) {mStatus = STATUS_OPEN;invalidate();}});// init close animatorcloseAnimator = new ValueAnimator();openAnimator.setInterpolator(accelerateInterpolator);closeAnimator.setDuration(duration);closeAnimator.addUpdateListener(animatorUpdateListener);closeAnimator.addListener(new AnimatorListenerAdapter() {@Overridepublic void onAnimationStart(Animator animation) {mStatus = STATUS_PROCESS;}@Overridepublic 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 barmPaint.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 iconmDstRectF.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 textif (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
最后,需要将 startOpen 和 startClose 方法暴露给外部,方便调用。在其内部就是调用两个属性动画而已。
/*** 判断搜索栏是否为打开状态** @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();}
源码地址:
https://github.com/yuqirong/FlexibleSearchBar
到这里就结束啦
