Android UI进阶之旅5--Material Design之TextInputLayout

前言

TextInputLayout可以轻松与EditText结合实现一些炫酷的效果,例如一些常见的:

  1. Hint动画
  2. 错误提示
  3. 字数计数

基本使用

首先需要有一个布局:

<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, "字数不能大于6", 6));

        //开启计数
        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的错误提示、字数统计功能,基本的使用都比较简单。

  1. 在TextInputLayout可以轻松地通过getEditText方法找到它所包裹的EditText。、
  2. 在显示错误的时候,需要先设置错误的提示,每次显示的时候都要设置。
  3. 大部分属性都可以通过xml的方式设置,这里通过代码动态设置只是为了方便演示。

TextInputLayout源码分析

作为一个父容器,TextInputLayout继承了线性布局:

public class TextInputLayout extends LinearLayout {

}

下面来看看它的构造函数:

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;

    //初始化一些参数
}

其中,我们关心一下 颜色渐变的核心代码:

/**
 * 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);
}

这个方法就是根据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内部就已经给EditText添加了TextWatcher,用于字数的处理:

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开发进阶

我的群欢迎大家进来探讨各种技术与非技术的话题,有兴趣的朋友们加我私人微信huannan88,我拉你进群交(♂)流(♀)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,527评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,314评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,535评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,006评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,961评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,220评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,664评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,351评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,481评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,397评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,443评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,123评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,713评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,801评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,010评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,494评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,075评论 2 341

推荐阅读更多精彩内容