循环遍历并保留android中的变量值

时间:2019-04-21 08:58:41

标签: android loops

如何在Android编程中创建循环以及如何在每次按钮单击事件之后增加变量值?我想为每次按钮单击保留变量“ over”值的值。

我的代码如下:

Button btnScore = (Button) findViewById(R.id.ScoreButton);

btnScore.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (RadioButton1.ischecked()){
            int over = 0;
            if (RadioRavi.ischecked()){
                EditText e12 = (EditText)findViewById(R.id.editText12);                        
               over = over + 1; //I want this loop for four times i.e. after four times 

               //button click it should have the value of 4;
               //problem is that when each time when i click button btnScore then it 
               //initializes variable "over" to 0;

               e12.setText(String.valueOf(over));
               //I want when I click button btnScore four times then 
               //variable "over" should contain the value "4".    
               //for each button click the value of over should be increase by 1.   
     }
}

我希望每次单击按钮时循环都会继续。我的意思是说,单击按钮之间必须保留变量“ over”值。

1 个答案:

答案 0 :(得分:0)

据我了解,您希望在每次单击按钮时增加价值。

所以您需要这样的东西。

Button btnScore = (Button) findViewById(R.id.ScoreButton);
EditText e12 = (EditText)findViewById(R.id.editText12);
int over = 0;

btnScore.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (RadioButton1.ischecked()){
            if (RadioRavi.ischecked()){

               //Select one of the solutions :)

               //Solution 1:
               over = over + 1;
               e12.setText(String.valueOf(over));

               //Solution 2:
               over++;
               e12.setText(String.valueOf(over));

               //Solution 3:
               e12.setText(String.valueOf(over++));

     }

}