TextInputLayout的使用
程序员文章站
2022-05-31 07:54:43
...
TextInputLayout是具有meteria design效果的编剧框,使用起来效果会比普通的EditText更加漂亮。
基本使用就是在TextInputLayout里面放置一个EditText即可,注意它只接受一个子view那就是EditText,布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="teststatusbar.com.xn.testnavigation.EtActivity">
<android.support.design.widget.TextInputLayout
android:id="@+id/user_input"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="200dp"
app:counterEnabled="true"
app:counterMaxLength="6"
app:hintEnabled="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/password_input"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
app:counterEnabled="true"
app:counterMaxLength="6"
app:hintEnabled="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
app:counterEnabled=”true”这个属性表示将输入的字符进行计数,这样在EditText的右下角就有了计数的文字。 app:counterMaxLength=”6”这个属性表示最大的输入数量为6。
下面直接上代码:
public class EtActivity extends AppCompatActivity {
TextInputLayout userInputLayout;
TextInputLayout passInputLayout;
TextWatcher watcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_et);
watcher = new wather();
userInputLayout = (TextInputLayout) findViewById(R.id.user_input);
passInputLayout = (TextInputLayout) findViewById(R.id.password_input);
userInputLayout.getEditText().addTextChangedListener(watcher);
userInputLayout.getEditText().addTextChangedListener(watcher);
}
class wather implements TextWatcher {
@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 (userInputLayout.getEditText().getText().toString().length() > 6 ||
passInputLayout.getEditText().getText().toString().length() > 6) {
userInputLayout.setErrorEnabled(true);
passInputLayout.setErrorEnabled(true);
passInputLayout.setError("输入字符必须少于6");
userInputLayout.setError("输入字符必须少于6");
}else{
userInputLayout.setErrorEnabled(false);
passInputLayout.setErrorEnabled(false);
}
}
}
}
userInputLayout.setErrorEnabled(true)是和passInputLayout.setError(“输入字符必须少于6”)配合使用的,设置错误,我们在上面是判断输入字符的数量,如果超过6就弹出错误字符。