Simple Edittext Math Android

2019-09-20 17:58发布

问题:

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 is done using the edittext boxes it can add the two together and output the answer in a textview. I'd post my code here, but it just isn't any good. Can anyone provide an example of how to take two edittext boxes, assign a textwatcher to both, then put the output into a textview. Also, please keep in mind that this is eventually going to use multiple edittext boxes while autoupdating each other. This would be similar to creating forumulas in Microsoft excel and having them update immediately. One of the main problems I seem to have is catching the numberformatexception when just one is empty. Thank you for your time.

回答1:

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

public class MainActivity extends Activity implements TextWatcher {

TextView tvResult;
EditText tvNumberOne, tvNumberTwo;

@Override
protected void onCreate(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);

}

@Override
public void afterTextChanged(Editable s) {

    int numOne = 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));

}

@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

}

}