简体   繁体   中英

Android Studios: How do I make a code that allows my app to do a certain action after a written number of clicks?

I understand the OnClickListener to some extent, and I understand that you can add what action you want the button to do after one click, but how do I make the button initiate an action after 5 clicks for example.

Keep an instance field which tracks the number of times pressed, then in your onClickListener just use that same if statement So your instance field could look like this:

private int counter = 0;

Then in your onclick listener:

counter++;
if(counter > 5) {
    //do the thing, call a method, whatever
 }

If you are looking for permanent storage, to keep track of the number of times it has been pressed that will persist after a user closes the app, use SharedPreferences, but I don't think that's what you are looking for here so I won't include the code.

If you aren't familiar with an instance field, its just a fancy word for a global variable(Yes Java purists I know that's not technically accurate). Just declare it right below your class declaration, and not inside any method.

public class MainActivity extends AppCompatActivity {

//instance fields go here
private int counter = 0;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM