bombaye125 bombaye125 - 3 months ago 31
Android Question

try to count onclick android

I need to count clicks and display number of clicks on

textView2
and my code just displays the number 4. I used a while loop to check the number of clicks.

public void Clicks(View v){
final TextView answerLabel = (TextView)findViewById(R.id.textView1); //show text from answer variable.
TextView count = (TextView) findViewById(R.id.textView2); //display click count.
String answer = null;
int i = 0;
while(i < 5){ // I allow user click just 5 time.

switch (v.getId()){
case R.id.button1 :
answer= "ROCK";
answerLabel.setText(answer);
count.setText(String.valueOf(i));
i++;
break;
case R.id.button2 :
answer = "SCISSOR";
answerLabel.setText(answer);
count.setText(String.valueOf(i));
i++;
break;
case R.id.button3 :
answer = "PAPER";
answerLabel.setText(answer);
count.setText(String.valueOf(i));
i++;
break;
}
}
}


How do I display it properly?

Answer

you should put int i = 0; outside of onClick at class level and start it at 1

public int i = 1;

then in onClick use an if statement

   if(i <= 5)
{
switch (v.getId()){
        case R.id.button1 :
           answer= "ROCK";
           answerLabel.setText(answer);
           count.setText(String.valueOf(i));
           i++;
        break;
        case R.id.button2 :
         answer = "SCISSOR";
         answerLabel.setText(answer);
         count.setText(String.valueOf(i));
         i++;
         break;
        case R.id.button3 :
        answer = "PAPER";
        answerLabel.setText(answer);
        count.setText(String.valueOf(i));
        i++;
        break;
        }
}
Comments