Reputation: 1980
I have implemented press back twice to exit an activity. But the problem is i have to copy and paste the same code in every activity to make it work for every activity. I can't make a common class and put my implementation because activities already extends AppCompatActivity, and as per i know; multiple inheritance is not supported. So how do i do this
This is my implementation, suggestions are welcome.
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Upvotes: 0
Views: 102
Reputation: 1700
Don't listen to people telling you to create a static method. Instead, create a custom Activity class and make all of your classes extend that class. In that class put your custom onBackPressed functionality.
Another option is to go single activity with multiple fragments where you only need the back press implementation in one place.
Upvotes: 0
Reputation: 29
Create your own custom (BaseActivity extends AppCompatActivity) and put your OnBackPressed() implementation in BaseActivity and then extend all activities from BaseActivity.
Upvotes: 0
Reputation: 1649
First override back click listener:
@Override
public void onBackPressed() {
super.onBackPressed();
}
remove the super.onBackPressed();
add this code:
private static final int MIN_TIME_INTERVAL_BETWEEN_BACK_CLICKS = 2000; // # milliseconds, desired time passed between two back presses.
private long backPressedTime;
@Override
public void onBackPressed() {
if (backPressedTime + MIN_TIME_INTERVAL_BETWEEN_BACK_CLICKS > System.currentTimeMillis()) {
finishAffinity();
return;
}
else {
Toast.makeText(this, "Tap back button in order to exit", Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
Upvotes: -1
Reputation: 23277
You can make your own custom Activity
that extends AppCompatActivity
and put your implementation in there and then let each of your other activities extend that custom Activity
instead of AppCompatActivity
. this is not multiple inheritence
Upvotes: 3