Android仿華為應(yīng)用市場(chǎng)伸縮的搜索欄
關(guān)于搜索欄,可以說各種 app 都有不同的樣式。影響比較深刻的就有華為應(yīng)用市場(chǎng)的搜索欄(同樣,簡書的搜索欄也是類似的)。
而今天,就是帶你來實(shí)現(xiàn)華為應(yīng)用市場(chǎng)那樣的搜索欄。
我們先放上我們實(shí)現(xiàn)的效果圖吧:

怎么樣,想不想學(xué)?
我們先來簡述一下實(shí)現(xiàn)的思路吧,其實(shí)并不復(fù)雜。
首先,在搜索欄還未打開時(shí),先確定半徑 R ,然后假設(shè)一個(gè)變量 offset 用來動(dòng)態(tài)改變搜索欄的寬度。如圖所示:

所以可以得到一個(gè)公式:offset = total width - 2 * R ;
那么顯而易見,offset 的取值就在 [0, total width - 2 * R] 之間了。
所以,我們可以借助屬性動(dòng)畫來完成這數(shù)值的變化。在調(diào)用 invalidate() 進(jìn)行重繪,達(dá)到動(dòng)態(tài)增加搜索欄寬度的效果。反之,關(guān)閉搜索欄也是同理的。
那么下面就用代碼來實(shí)現(xiàn)它咯!
attrs
關(guān)于自定義的屬性,我們可以想到的有搜索欄的背景顏色、搜索欄的位置(左或右)、搜索欄的狀態(tài)(打開或關(guān)閉)等。具體的可以查看下面的 attrs.xml 。根據(jù)英文應(yīng)該能知道對(duì)應(yīng)屬性的作用了。
<?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
而在構(gòu)造器中,肯定就是初始化一些 attrs 中的全局變量了,這也不是重點(diǎn),都是機(jī)械式的代碼。
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 方法中是兩個(gè)屬性動(dòng)畫,打開和關(guān)閉動(dòng)畫。非常 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 中的代碼也是很機(jī)械的,基本上都是同一個(gè)套路了。
@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 中先畫了搜索欄的背景,然后是搜索欄的圖標(biāo),最后是搜索欄的提示文字。
畫背景的時(shí)候,是需要根據(jù)搜索欄在左邊還是右邊的位置來確定值的。
而畫圖標(biāo)的時(shí)候,是根據(jù)搜索欄關(guān)閉時(shí)那個(gè)圓的內(nèi)切正方形作為 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 方法暴露給外部,方便調(diào)用。在其內(nèi)部就是調(diào)用兩個(gè)屬性動(dòng)畫而已。
/*** 判斷搜索欄是否為打開狀態(tài)** @return*/public boolean isOpen() {return mStatus == STATUS_OPEN;}/*** 判斷搜索欄是否為關(guān)閉狀態(tài)** @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();}/*** 關(guān)閉搜索欄*/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
到這里就結(jié)束啦
