可以伸縮的搜索欄,模仿華為應用市場

博文出處:可以伸縮的搜索欄,模仿華為應用市場,歡迎大家關注我的博客,謝謝!

本項目的 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 中的代碼也是很機械的,基本上都是同一個套路了。

@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

最后,需要將 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 中的代碼即可。

有問題的可以在下面留言。沒問題的老鐵可以來一波 star 。

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,677評論 25 708
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協議。它實...
    香橙柚子閱讀 24,003評論 8 183
  • 丁香不會老,淡淡流年香。 朵朵綴星空,愿得讀書郎! 花瓣猶星子,香滿紫紗衣。 夜望群星閃,天地五月溪。
    昊水長天閱讀 229評論 0 0
  • 文/昔秋水 圖/網絡 我,坐在斜陽淺照的石階上,望著這個眼睛清亮的小孩專心地做一件事;是的,我愿意等上一輩子的...
    明珠愛寫作閱讀 255評論 2 5