Reputation: 1139
I want to override onBackPressed() and I have this code in all my activities
int backpress=0;
public void onBackPressed(){
backpress = (backpress + 1);
if (backpress>1) {
this.finish();
}else{
Toast.makeText(getApplicationContext(), R.string.finish, Toast.LENGTH_SHORT).show();
}
}
But I only want to override the function one time if it's possible. Whats the proper way?
Upvotes: 3
Views: 760
Reputation: 82948
Create a Base activity and define this method there. Like
public class BaseActivity extends Activity {
private int backpress = 0;
@Override
public void onBackPressed() {
backpress = (backpress + 1);
if (backpress > 1) {
this.finish();
} else {
Toast.makeText(getApplicationContext(), R.string.finish,
Toast.LENGTH_SHORT).show();
}
}
}
And extend this BaseActivity instead of Activity ino your activity. Like
// Just override BaseActivity instead of Activity class.
public class MyActivity extends BaseActivity {
// Do you task
}
Upvotes: 3