首页 > 解决方案 > 检查特定字符串的 EditText 内容

问题描述

大家,

我在网上找了很久,但我找不到解决办法-所以我直接问专业人士,哈哈。我的问题是我想检查 EditText 的字符。我正在编写一个计算器,这里不应该在 EditText 中显示几个计算运算符。我当然可以以不同的方式解决这个问题,但是有没有可以检查 EditText 字符串的函数?

这里将整个计算写入一个 EditText。

谢谢!

标签: javaandroidfunction

解决方案


试试这个功能..把它放在你的运营商的每个监听器中


 private void checkOperators(){

    //change the id with the id of your EditText
    EditText myEditText = findViewById(R.id.idEditText);

    //Get the last char
    String lastChar = myEditText.getText().toString().substring(myEditText.length());

    if (lastChar.equals("+") || lastChar.equals("*") || lastChar.equals("-") || lastChar.equals("/")){

        //Delete the first operator if they exist
        myEditText.setText(myEditText.getText().toString().substring(0,myEditText.length()-1);
    }


    // replace "newOperator" with your operator
    myEditText.setText(myEditText.getText().append(newOperator);

}


推荐阅读