vishwas vishwas - 5 months ago 86
Android Question

How to make onBackPressed method in one class and call it where necessary in android?

I have to implement onBackPressed in all the activity ,so that I think to make a singleton class and implement onBackPressed method in that and call that method where necessary.How can I DO that.

code:-

/*This method functions when user press device back button*/
@Override
public void onBackPressed() {
long currentTime = System.currentTimeMillis();

if ((currentTime - lastPressTime) < 2000) {
// Double Press
moveTaskToBack(true);
} else {
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
lastPressTime = currentTime;
}
}

Answer

You can create one class named BaseActivity which extends AppCompatActivity. All your activity will now extend to this BaseActivity class instead of AppCompatActivity. So whenever you have not defined onBackPressed it will call it's parent class method and perform it's operations.

public class BaseActivity extends AppCompatActivity  {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.translate, R.anim.left_to_right_simple);
}

}

If you want to customise this method for one class then just need to override this method in that respective class. For other classes it will work same as defined in BaseActivity

Your all activity will be something like this.

public class HomeScreen extends BaseActivity{
  @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   }

}