I am trying to recalculate every time the user changes input so I have used a TextWatcher. It calculates when the application starts when text is changed it does not recalculate when I have entered a new value. Could someone tell me what I am doing wrong? Is using the “onTextChanged” correct and would I have to put the whole calculation in that procedure or just call the variables one and two variable that change? Please ignore the spinner.
Thanks in advance.
public class AndroidActivity extends Activity implements 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));
}
}
It seems you are missing binding
textviewwithTextWatcher.You need to do something like to bind
textviewwithTextWatcher:Read this tutorial for simple example.