Android UI進階之旅5--Material Design之TextInputLayout

前言

TextInputLayout可以輕松與EditText結(jié)合實現(xiàn)一些炫酷的效果辕近,例如一些常見的:

  1. Hint動畫
  2. 錯誤提示
  3. 字數(shù)計數(shù)

基本使用

首先需要有一個布局:

<android.support.design.widget.TextInputLayout
    android:id="@+id/til_input"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:hintAnimationEnabled="true">

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入用戶名"/>

</android.support.design.widget.TextInputLayout>

hintAnimationEnabled屬性是設置是否開啟Hint的動畫。

需要注意的是骑丸,TextInputLayout必須包含一個EditText。

下面是一個基本的例子:

public class TextInputMainActivity extends AppCompatActivity {

    private TextInputLayout til_input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_input);

        til_input = (TextInputLayout) findViewById(R.id.til_input);
        til_input.getEditText().addTextChangedListener(new MaxTextTextWatcher(til_input, "字數(shù)不能大于6", 6));

        //開啟計數(shù)
        til_input.setCounterEnabled(true);
        til_input.setCounterMaxLength(6);

    }

    class MaxTextTextWatcher implements TextWatcher {

        private TextInputLayout mTextInputLayout;
        private String mErrorString;
        private int maxTextCount;

        public MaxTextTextWatcher(TextInputLayout textInputLayout, String errorString, int maxTextCount) {
            mTextInputLayout = textInputLayout;
            mErrorString = errorString;
            this.maxTextCount = maxTextCount;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String str = mTextInputLayout.getEditText().getText().toString().trim();
            if (!TextUtils.isEmpty(str)) {
                if (str.length() > maxTextCount) {
                    //顯示錯誤
                    //設置錯誤提示
                    mTextInputLayout.setError(mErrorString);
                    mTextInputLayout.setErrorEnabled(true);
                } else {
                    //關閉錯誤
                    mTextInputLayout.setErrorEnabled(false);
                }
            }
        }
    }
}

在這個例子里面芯杀,我們利用了TextInputLayout的錯誤提示肤舞、字數(shù)統(tǒng)計功能,基本的使用都比較簡單项炼。

  1. 在TextInputLayout可以輕松地通過getEditText方法找到它所包裹的EditText担平。、
  2. 在顯示錯誤的時候锭部,需要先設置錯誤的提示暂论,每次顯示的時候都要設置。
  3. 大部分屬性都可以通過xml的方式設置拌禾,這里通過代碼動態(tài)設置只是為了方便演示取胎。

TextInputLayout源碼分析

作為一個父容器,TextInputLayout繼承了線性布局:

public class TextInputLayout extends LinearLayout {

}

下面來看看它的構(gòu)造函數(shù):

public TextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {

    //檢查主題是不是AppCompatTheme
    ThemeUtils.checkAppCompatTheme(context);

    //設置線性布局的布局方向
    setOrientation(VERTICAL);
    setWillNotDraw(false);
    setAddStatesFromChildren(true);

    //添加輸入框的幀布局
    mInputFrame = new FrameLayout(context);
    mInputFrame.setAddStatesFromChildren(true);
    addView(mInputFrame);

    //Hint的動畫相關湃窍,包括字體大小以及顏色的變化動畫
    mCollapsingTextHelper.setTextSizeInterpolator(AnimationUtils.FAST_OUT_SLOW_IN_INTERPOLATOR);
    mCollapsingTextHelper.setPositionInterpolator(new AccelerateInterpolator());
    mCollapsingTextHelper.setCollapsedTextGravity(Gravity.TOP | GravityCompat.START);

    mHintExpanded = mCollapsingTextHelper.getExpansionFraction() == 1f;

    //初始化一些參數(shù)
}

其中闻蛀,我們關心一下 顏色漸變的核心代碼:

/**
 * Blend {@code color1} and {@code color2} using the given ratio.
 *
 * @param ratio of which to blend. 0.0 will return {@code color1}, 0.5 will give an even blend,
 *              1.0 will return {@code color2}.
 */
private static int blendColors(int color1, int color2, float ratio) {
    final float inverseRatio = 1f - ratio;
    float a = (Color.alpha(color1) * inverseRatio) + (Color.alpha(color2) * ratio);
    float r = (Color.red(color1) * inverseRatio) + (Color.red(color2) * ratio);
    float g = (Color.green(color1) * inverseRatio) + (Color.green(color2) * ratio);
    float b = (Color.blue(color1) * inverseRatio) + (Color.blue(color2) * ratio);
    return Color.argb((int) a, (int) r, (int) g, (int) b);
}

這個方法就是根據(jù)ratio摄杂,返回一個顏色值。如果是0循榆,那么返回color1析恢,如果是1,那么返回color2秧饮。這是一個線性變化的過程映挂。

重寫addView了,如果是EditText盗尸,那么就需要手動生成一個幀布局:

@Override
public void addView(View child, int index, final ViewGroup.LayoutParams params) {
    if (child instanceof EditText) {
        mInputFrame.addView(child, new FrameLayout.LayoutParams(params));

        // Now use the EditText's LayoutParams as our own and update them to make enough space
        // for the label
        mInputFrame.setLayoutParams(params);
        updateInputLayoutMargins();

        setEditText((EditText) child);
    } else {
        // Carry on adding the View...
        super.addView(child, index, params);
    }
}

另外TextInputLayout是通過兩種方式添加文字的柑船,一種是直接利用畫筆畫布繪制,一種是直接new一個TextView泼各,這也是我們自定義View的基本功鞍时。

TextInputLayout內(nèi)部就已經(jīng)給EditText添加了TextWatcher,用于字數(shù)的處理:

mEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        updateLabelState(true);
        if (mCounterEnabled) {
            updateCounter(s.length());
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

如果覺得我的文字對你有所幫助的話扣蜻,歡迎關注我的公眾號:

公眾號:Android開發(fā)進階

我的群歡迎大家進來探討各種技術與非技術的話題逆巍,有興趣的朋友們加我私人微信huannan88,我拉你進群交(♂)流(♀)莽使。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末锐极,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子芳肌,更是在濱河造成了極大的恐慌灵再,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件亿笤,死亡現(xiàn)場離奇詭異翎迁,居然都是意外死亡,警方通過查閱死者的電腦和手機净薛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門汪榔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人罕拂,你說我怎么就攤上這事舱权』床” “怎么了儒陨?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵蜜猾,是天一觀的道長。 經(jīng)常有香客問我柿菩,道長戚嗅,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任懦胞,我火速辦了婚禮蚯根,結(jié)果婚禮上颅拦,老公的妹妹穿的比我還像新娘。我一直安慰自己碌秸,他們只是感情好,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布鸦致。 她就那樣靜靜地躺著分唾,像睡著了一般绽乔。 火紅的嫁衣襯著肌膚如雪折砸。 梳的紋絲不亂的頭發(fā)上沙峻,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機與錄音竖螃,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的输虱。 我是一名探鬼主播宪睹,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼鹅很!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起促煮,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎整袁,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡是尔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年宣渗,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片梨州。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡痕囱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出暴匠,到底是詐尸還是另有隱情鞍恢,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布每窖,位于F島的核電站帮掉,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏窒典。R本人自食惡果不足惜蟆炊,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望瀑志。 院中可真熱鬧涩搓,春花似錦、人聲如沸劈猪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽战得。三九已至充边,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間常侦,已是汗流浹背浇冰。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留刮吧,地道東北人湖饱。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像杀捻,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蚓庭,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容