总共2个textviews

时间:2011-06-08 17:18:43

标签: android

private int ScoreCount;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.score);

    final TextView TotalScore = (TextView) findViewById(R.id.TotalScore);
    final TextView One = (TextView) findViewById(R.id.Score1);

    One.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            ScoreCount++;
            Front9.setText("" + ScoreCount);
        }
    });

如果我在两个textviews中填写一个随机数,我想要总数中的2个数字的总和。 我怎么做。是我添加正确方法的代码。 我知道onclicklistener不是正确的方法,而是使用什么。

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是TextWatcher http://developer.android.com/reference/android/text/TextWatcher.html

假设您有代码来处理每个得分TextView的增量,请使用TextWatcher将每个TextView连接起来

One.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int score1 = Integer.parseInt(One.getText());
        int score2 = Integer.parseInt(Two.getText());
        FrontNine.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

    }
});

编辑 - 显然我误解了这个问题。要增加每个分数,使用单击处理程序是一种可接受的方法。有关完整示例,请参阅上面的代码。忽略上面的评论和代码。

private int scoreTotal1;
private int scoreTotal2;
private int overallTotalScore;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.score);

    scoreTotal1 = 0;
    scoreTotal2 = 0;
    overallTotalScore = 0;

    final TextView textViewtotalScore = (TextView) findViewById(R.id.TotalScore);
    final TextView textViewOne = (TextView) findViewById(R.id.Score1);
    final TextView textViewTwo = (TextView) findViewById(R.id.Score2);

    textViewOne.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            scoreTotal1++;
            overallTotalScore = scoreTotal1 + scoreTotal2;
            textViewOne.setText(String.valueOf(scoreTotal1));
            textViewTotalScore.setText(String.valueOf(overallTotalScore));
        }
    });

    textViewTwo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            scoreTotal2++;
            overallTotalScore = scoreTotal1 + scoreTotal2;
            textViewTwo.setText(String.valueOf(scoreTotal2));
            textViewTotalScore.setText(String.valueOf(overallTotalScore));
        }
    });
}