效果图:

第三十一篇-TextInputLayout(增强文本输入)的使用

密码使用的是增强文本输入类型,当密码长度小于6或者密码长度大于10的时候就会给出提示。

main.xml

第三十一篇-TextInputLayout(增强文本输入)的使用

当添加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("");
                }

            }
        });
    }
}
View Code

相关文章:

  • 2021-06-09
  • 2021-11-25
  • 2022-12-23
  • 2021-06-29
  • 2021-09-18
  • 2021-06-03
  • 2022-12-23
  • 2021-09-30
猜你喜欢
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-11-04
  • 2021-07-07
相关资源
相似解决方案