0

我需要计算点击次数并显示点击次数,textView2而我的代码只显示数字 4。我使用了一个 while 循环来检查点击次数。

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;
        }
    }   
}

如何正确显示?

4

3 回答 3

0

更改休息以继续;因为 break 会停止循环

但在这种情况下,您每次点击时都会增加。

所以你根本不需要循环。

你需要 if 条件!例如 if(i<5) 并使 i 成为全局变量

于 2013-09-18T01:21:52.740 回答
0

你应该把 int i = 0; 在类级别的 onClick 之外并从 1 开始

public int i = 1;

然后在 onClick 中使用 if 语句

   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;
        }
}
于 2013-09-18T01:22:00.937 回答
0

搜索你的布局膨胀的 onCreate() 方法,然后试试这个:

@Override
public void onCreate(Bundle savedInstanceState) {
...

Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
int i =0;
button1.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View v) {
            answer= "ROCK";
                            answerLabel.setText(answer);
                            count.setText(String.valueOf(i));
                            i++;
        }
    });
button2.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View v) {
            answer= "SCISSOR";
                            answerLabel.setText(answer);
                            count.setText(String.valueOf(i));
                            i++;
        }
    });
button3.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View v) {
            answer= "PAPER";
                            answerLabel.setText(answer);
                            count.setText(String.valueOf(i));
                            i++;
        }
    });
于 2013-09-18T01:39:59.917 回答