博文出處:可以伸縮的搜索欄,模仿華為應用市場,歡迎大家關注我的博客,謝謝!
本項目的 GitHub 地址:https://github.com/yuqirong/FlexibleSearchBar
關于搜索欄,可以說各種 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() {
@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
中的代碼也是很機械的,基本上都是同一個套路了。
@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 的。
最后畫提示文字沒什么好講的了,都是定死的代碼。
@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
最后,需要將 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();
}
End
到這也差不多了,該講的都講了,這篇寫得真 TMD 簡潔。至于和 AppBarLayout
的混合使用,見 GitHub 中的代碼即可。
有問題的可以在下面留言。沒問題的老鐵可以來一波 star 。
FlexibleSearchBar:https://github.com/yuqirong/FlexibleSearchBar