欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android中EditText只允许输入汉字(过滤汉字)

程序员文章站 2022-06-14 22:08:03
...

FilterUtils中添加过滤方法:

public class FilterUtils {

 public static String filterChinese(String str){
        String regEx="[^\\u4E00-\\u9FA5]";
        Pattern p=Pattern.compile(regEx);
        Matcher matcher = p.matcher(str);
        return matcher.replaceAll("").trim();
    }

}

 Edittext的TextWatcher监听方法中使用:

public class ChineseActivity extends AppCompatActivity implements TextWatcher {
    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chinese);
        et=findViewById(R.id.et);
        et.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
       String s=FilterUtils.filterChinese(et.getText().toString().trim());
        Log.e("=====dggfh===",s);

    }
}