您的位置:首页 > 移动开发 > Android开发

Android开发之TextInputLayout的简单使用(增强EditText)

2017-05-18 15:09 716 查看
前言:TextInputLayout是来增强EditText的,也是Google封装的很强大吧!从官方文档中可以看到TextInputLayout继承自LinearLayout,一般都是把EditText和它的子类包含在内,以便用户在输入文本时,且当提示文本被隐藏时显示一个浮动的标签。当然了它也支持通过setErrorEnabled(boolean)和setError(CharSequence)方法来显示错误提示,总之功能很强大效果很炫!但是目前来看,没看到有多少主流的app使用这一技术!算了不纠结了,接下来就由我带领大家来探讨一下TextInputLayout的用法。

-------------------分割线---------------------------

先看一下效果图:



-------------------分割线---------------------------

使用TextInputLayout之前一定要添加
design 依赖:

compile 'com.android.support:design:25.2.0'-------------------分割线---------------------------

使用起来也十分简单,来先看一下如何布局:
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true"
app:hintAnimationEnabled="true">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" />
</android.support.design.widget.TextInputLayout>-------------------分割线---------------------------

然后再看逻辑代码!
开启计数:textInputLayout.setCounterEnabled(true);

最大输入限制数:textInputLayout.setCounterMaxLength(10);

监听检测长度:textInputLayout.getEditText().addTextChangedListener(new ...),其中最关键的是要实现TextWatcher的接口,重写里面的回调方法,来实现监听长度!

看下效果图:



-------------------分割线---------------------------

具体来看下完整代码:

import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;

public class MainActivity extends AppCompatActivity {

private TextInputLayout textInputLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textInputLayout = (TextInputLayout) findViewById(R.id.textInputLayout);
//检测长度应该低于6位数
textInputLayout.getEditText().addTextChangedListener(new MinLengthTextWatcher(textInputLayout, "长度应低于6位数!"));

//开启计数
textInputLayout.setCounterEnabled(true);
textInputLayout.setCounterMaxLength(10);//最大输入限制数
}

class MinLengthTextWatcher implements TextWatcher {

private TextInputLayout textInputLayout;
private String errorStr;

public MinLengthTextWatcher(TextInputLayout textInputLayout, String errorStr) {
this.textInputLayout = textInputLayout;
this.errorStr = errorStr;
}

@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) {
// 文字变化后回调
if (textInputLayout.getEditText().getText().toString().length() <= 6) {
textInputLayout.setErrorEnabled(false);
} else {
textInputLayout.setErrorEnabled(true);
textInputLayout.setError(errorStr);
}
}
}
}-------------------分割线---------------------------
ok!我们下节开始讲解ToolBar。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: