a total sum of 2 textviews
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 On开发者_如何转开发ClickListener() {
public void onClick(View v) {
ScoreCount++;
Front9.setText("" + ScoreCount);
}
});
If i fill a random number in both textviews, i want a sum of the 2 numbers in the totalscore. how do i do that. is the code i added the right way to do this. i know that the onclicklistener is not the right way but what to use instead.
I think what you are looking for is a TextWatcher http://developer.android.com/reference/android/text/TextWatcher.html
Assuming you have code to take care of incrementing each of your score TextViews, hook up each of the TextViews with a TextWatcher like so
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
}
});
Edit - Apparently I misunderstood the question. To increment each of the scores, using a click handler is an acceptable approach. See code above for the complete example. Disregard the comments and code above.
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));
}
});
}
精彩评论