TextWatcher未在活动中更新的问题

时间:2013-01-15 22:29:42

标签: java android

我试图在每次用户更改输入时重新计算,因此我使用了TextWatcher。它会计算应用程序在文本更改时的启动时间,但在输入新值时不会重新计算。有人能告诉我我做错了什么吗?使用“onTextChanged”是否正确,我是否必须将整个计算放在该过程中,或者只调用变量一个和两个变量变量?请忽略微调器。  提前谢谢。

public class AndroidActivity extends Activity实现了TextWatcher {

  private Spinner spinner1; 

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pounds);
    addListenerOnSpinnerItemSelection();

    int one = 0;
    int two = 0;



    try{
      EditText one100lbs = (EditText) findViewById(R.id.one100lbs);
      one = Integer.valueOf(one100lbs.getText().toString().trim());
    }
    catch (NumberFormatException e)
    {
      one = -1;
    }

    try{
      EditText tenPounds = (EditText) findViewById(R.id.tenPounds);
      two = Integer.valueOf(tenPounds.getText().toString().trim()); 
    }
    catch (NumberFormatException e)
    {
      two = -1;
    }

    int result = one + two;

    TextView textView = (TextView) findViewById(R.id.editText1);
    textView.setText(String.valueOf(result)); 




}

//create spinner 
public void addListenerOnSpinnerItemSelection() {
    spinner1 = (Spinner) findViewById(R.id.other_spinner);
    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
  }

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

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {    
    // TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

    int one = 0;
    int two = 0;

    try{
      EditText one100lbs = (EditText) findViewById(R.id.one100lbs);
      one = Integer.valueOf(one100lbs.getText().toString().trim());
    }
    catch (NumberFormatException e)
    {
      one = -1;
    }

    try{
      EditText tenPounds = (EditText) findViewById(R.id.tenPounds);
      two = Integer.valueOf(tenPounds.getText().toString().trim()); 
    }
    catch (NumberFormatException e)
    {
      two = -1;
    }

    int result = one + two;

    TextView textView = (TextView) findViewById(R.id.editText1);
    textView.setText(String.valueOf(result)); 
}

}

1 个答案:

答案 0 :(得分:0)

您似乎错过了textviewTextWatcher的约束{。}}。

您需要执行类似textviewTextWatcher

绑定的操作
text = (EditText)findViewById(R.id.yourTextField);
text.addTextChangedListener(this);

阅读此tutorial以获取简单示例。