如何递增每个得分TextViews?

时间:2011-06-09 13:10:33

标签: android

我正在制作记分牌并希望跟踪总分。 如果我在两个文本视图中填写一个随机数,我想要总数为2的数字作为总数的总和。我怎么做。在我之前的问题中,我有这个代码作为答案,但他们说我必须递增每个得分TextViews并使用TextWatcher连接每个TextViews。 如何递增每个得分TextViews?

enter image description here

    final TextView TotalScore = (TextView) findViewById(R.id.Total);
    final EditText One = (EditText) findViewById(R.id.Score1);
    final EditText Two = (EditText) findViewById(R.id.Score2);

    TotalSore.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int Score1 = Integer.parseInt((String) One.getText().toString());
            int Score2 = Integer.parseInt((String) Two.getText().toString());

            TotalScore.setText(String.valueOf(Score1 + Score2));
        }

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

        }

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

        }
    });

1 个答案:

答案 0 :(得分:0)

以下是如何增加一个:

String oneText = One.getText().toString();
int oneScore = Integer.parseInt(oneText);
++oneScore;
One.setText(oneScore+"");

您可以对Two

执行相同的操作

更新

如果您想更新总分,则应将TextWatcher同时应用于OneTwo

class MyTextWatcher implements TextWatcher {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int Score1 = Integer.parseInt((String) One.getText().toString());
        int Score2 = Integer.parseInt((String) Two.getText().toString());

        TotalScore.setText(String.valueOf(Score1 + Score2));
    }

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

    }

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

    }
}

One.addTextChangedListener(new MyTextWatcher());
Two.addTextChangedListener(new MyTextWatcher());