Simple Edittext Math Android

淺唱寂寞╮ 提交于 2020-01-07 08:29:29

问题


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

}

}



来源:https://stackoverflow.com/questions/26318972/simple-edittext-math-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!