效果图:
密码使用的是增强文本输入类型,当密码长度小于6或者密码长度大于10的时候就会给出提示。
main.xml
当添加TextInputLayout时,旁边会有一个下载符号,如果点不动,可以右键点击add to design,然后它会加载,加载完毕后,后面那个下载符号就消失了,可以拖动它到相应位置了。
然后可以在MainActivity.java中设置当状态改变时需要进行的操作:
textInputEditText.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(textInputEditText.getText().toString().length()>textInputLayout.getCounterMaxLength()|
textInputEditText.getText().toString().length()<6){
textInputLayout.setError("密码长度为6~10位");
}
else{
textInputLayout.setError("");
}
}
});
beforeTextChanged是状态改变前,onTextChanged是状态改变中,afterTextChanged是状态改变后,我们一般用最后一个。其中getCounterMaxLength的大小是在main.xml中设置的,我设置的是10.
MainActivity.java
package com.example.aimee.textinputlayouttest; import android.support.design.widget.TextInputEditText; 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 { TextInputLayout textInputLayout; TextInputEditText textInputEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textInputLayout=findViewById(R.id.textinputlayout1); textInputEditText=findViewById(R.id.textinputedit1); check(); } private void check(){ textInputEditText.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(textInputEditText.getText().toString().length()>textInputLayout.getCounterMaxLength()| textInputEditText.getText().toString().length()<6){ textInputLayout.setError("密码长度为6~10位"); } else{ textInputLayout.setError(""); } } }); } }