Aditya
Aditya

Reputation: 425

How to check the number of times the back button is pressed in android

I am aware that a method onBackPressed() exists in java to handle code when back button is pressed.

But I want to know if there is any method or variable which tells me the number of time the back button is pressed?

Upvotes: 0

Views: 315

Answers (2)

Changer
Changer

Reputation: 359

int counter;

@Override
public void onBackPressed() {
    super.onBackPressed(); //remove this line if you don't want to finish the activity on back press

    counter++;
    System.out.println("Back button pressed for" + counter + "times.");
}

Upvotes: 3

Priyaank
Priyaank

Reputation: 260

Create a counter variable and increment it in the onClick()

myButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
 counter++;
 myText.setText(“You click the Button “+count+” times now”);
}}

Upvotes: 0

Related Questions