如何动态地从edittext获取值?

时间:2013-05-15 23:30:06

标签: java android dynamic android-edittext

我尝试过不成功的搜索。我需要一个edittext,总是检查它的值是否正在改变,以及它是否包含某些东西。我看过一个OnTouch监听器,但它只是检查它是否“触摸”正确?

通过代码说明:

EditText a = (EditText) findViewById(R.id.MyID);
String check = a.getText().toString();
if(check.contains(" my String "))
{`//do something}
else{//keep checking until it contains specified string}

一个例子是“自动计算”按钮

ANSWER = 这适用于您的OnCreate方法。谢谢大家或指向我TextWatcher()

myEditText.addTextChangedListener(new TextWatcher()
        {
            public void afterTextChanged(Editable s){
                if(myEditText.getText().toString().equals(" my String")){
                    //do something

        }

                }

            public void beforeTextChanged(CharSequence s,int start,int count, int after){} 
            public void onTextChanged(CharSequence s, int start, int before, int count) {

         }
});

3 个答案:

答案 0 :(得分:1)

实施TextWatcher并在EditText上调用addTextChangedListener

答案 1 :(得分:0)

您需要设置TextWatcher。在Activity

中创建一个这样的类
private class TempWatcher implements TextWatcher {

@Override
public void afterTextChanged(Editable s) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) 
{   
     if (s.length() > 0) 
     {
          if(s.contains(" my String "))
           {`//do something}
     }
}

在初始化TextWatcher

后,将EditText附加到EditText这样的yourEditText.addTextChangedListener(new TempWatcher());
else

然后,每次文本更改时,此侦听器都将检查值。您甚至不需要{{1}},因为它会在文本更改时继续检查

答案 2 :(得分:0)

你想要的是TextWatcher以下是如何实现它:

    a.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(s.contains(" my String ")){
                //dosomething
             }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });