I am trying to display a winning message after the score reach 45 point.
I have used OnClickListener
to increase point and when the score reach 45 on text view i want to show a toast/pop up message.
public class Activity2 extends AppCompatActivity {
TextView txtView1, txtView2, txt_point1, txt_point2;
Button PointBtn, PointBtn2;
int count1 = 0;
public void scoreCount() {
count1 = count1++ + 15;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
txt_point1 =(TextView) findViewById(R.id.pointView1);
txt_point2 = (TextView) findViewById(R.id.pointView2);
txtView1 = (TextView) findViewById(R.id.txtView1);
txtView1.setText(getIntent().getStringExtra("player 1"));
txtView2 = (TextView) findViewById(R.id.txtView2);
txtView2.setText(getIntent().getStringExtra("player 2"));
PointBtn = findViewById(R.id.BtnPlus1);
PointBtn2 = findViewById(R.id.btnPlus2);
PointBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
scoreCount();
txt_point2.setText( count1+ "love");
if (count1==45){
Toast.makeText(Activity2.this,
"Player " +getIntent().getStringExtra("player 1" + " has won"),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Activity2.this, "You lose", Toast.LENGTH_SHORT).show();
}
}
});
3
Answers
You have wrong operators in the
scoreCount()
method. Don’t use increment operator++
, it incrementscount1
by one and adds 15. Use just+=
operator:Actually by
you are incrementing the variable by 16 and not 15. So remove
count1++ + 15
and make itcount1 + 15
. You may also use shorthand operator+=
.OR
Use next code for Score
and after it you can use Dialog window instead of Toast.makeText