Keep pressing a button so that a counter keeps adding by 1 every time

前端 未结 2 606
情歌与酒
情歌与酒 2021-01-29 09:12

I was thinking if there was a simple way to keep pressing the same button so that the counter keeps adding by 1 every time. So that if the button is clicked two times it will ha

相关标签:
2条回答
  • 2021-01-29 09:41

    Two problems with your code.

    1. You reset the counter on each click, it seems
    2. You have a single equals in your if statement, which is not a comparison

    You can try this instead

    public class MainActivity extends Activity 
        implements View.OnClickListener {
    
            private int counter;
    
            @Override 
            public void onClick(View v) {
                if (view.getId() == R.id.Spinbtn) { // change to your button id
                    counter++;
                } 
    
                if (counter >= 2) {
                   showcalcuation();
                } else {
                   // hide calculation? 
                } 
        } 
    
        ... 
            // in onCreate 
            button.setOnClickListener(this);
    
    0 讨论(0)
  • 2021-01-29 09:52

    First, make this global within your class:

    int counter = 0;  
    

    Then implement the button click event:

     final Button button = (Button) findViewById(R.id.Spinbtn);
              button.setOnClickListener(new View.OnClickListener() {
                   public void onClick(View view) {
                        if(view.getId() == R.id.Spinbtn){
                             if(counter == 2){
                                showcalcuation();
                             }else if(counter < 2){
                                counter += 1;
                             }
                        }
                   }
              });
    
    0 讨论(0)
提交回复
热议问题