Skip to content Skip to sidebar Skip to footer

Simple Edittext Math Android

new SO user here and I'm new to android as well. I need help doing a simple calculation between two edittext boxes - without a button, using a textwatcher, so that after the user

Solution 1:

I implemented a simple app - I hope it helps you.

publicclassMainActivityextendsActivityimplementsTextWatcher {

TextView tvResult;
EditText tvNumberOne, tvNumberTwo;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvResult = (TextView)findViewById(R.id.tvResult);
    tvNumberOne = (EditText)findViewById(R.id.tvNumberOne);
    tvNumberTwo = (EditText)findViewById(R.id.tvNumberTwo);

    tvNumberOne.addTextChangedListener(this);
    tvNumberTwo.addTextChangedListener(this);

}

@OverridepublicvoidafterTextChanged(Editable s) {

    intnumOne=0, numTwo = 0;
    try{
        numOne = Integer.valueOf(String.valueOf(tvNumberOne.getText()));
        numTwo = Integer.valueOf(String.valueOf(tvNumberTwo.getText()));
    }catch(Exception ex){
        Toast.makeText(getApplicationContext(), "Parsing error!",Toast.LENGTH_SHORT).show();
    }

    tvResult.setText(String.valueOf(numOne + numTwo));

}

@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub

}

@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub

}

}

Post a Comment for "Simple Edittext Math Android"