TextInputLayout 和 TextInputEditText 是属于 design 包里面的控件
呐,就是这个:compile ‘com.android.support:design:26.0.0-alpha1‘
这两者要结合使用,其实只用 TextInputLayout ,然后 TextInputEditText 用 EditText 替换好像也可以。
下面来看一个示例代码咯
布局文件如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/userNameLayout" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.design.widget.TextInputEditText android:id="@+id/userName" android:layout_width="match_parent" android:layout_height="wrap_content" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/passwdLayout" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.design.widget.TextInputEditText android:id="@+id/passwd" android:layout_width="match_parent" android:layout_height="wrap_content" /> </android.support.design.widget.TextInputLayout> </LinearLayout>
Activity的代码如下
private TextInputLayout userNameLayout; private TextInputEditText userName; private TextInputLayout passwdLayout; private TextInputEditText passwd; userNameLayout = (TextInputLayout) findViewById(R.id.userNameLayout); userName = (TextInputEditText) findViewById(R.id.userName); userNameLayout.setHint("请输入账号"); userName.addTextChangedListener(new 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 (s.length() < 3) { userNameLayout.setErrorEnabled(true); userNameLayout.setError("用户名不能小于3位"); } else { userNameLayout.setErrorEnabled(false); } } }); passwdLayout = (TextInputLayout) findViewById(R.id.passwdLayout); passwdLayout.setHint("请输入密码"); passwd = (TextInputEditText) findViewById(R.id.passwd); passwd.addTextChangedListener(new 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 (s.length() < 3) { passwdLayout.setErrorEnabled(true); passwdLayout.setError("密密不222能小于3位"); } else { passwdLayout.setErrorEnabled(false); } } }); }
其实也没什么,
主要的代码也就几行
userNameLayout.setHint("请输入账号");
这行代码,就是设置提示信息
passwdLayout.setErrorEnabled(true);
这行表示,启用错误提示,相应的,传入false就表示关闭错误提示。
passwdLayout.setError("密密不222能小于3位");
这个表示,具体的错误提示
时间: 2024-11-09 02:53:36