Sa1m0n
Sa1m0n

Reputation: 806

Android onBackPressed for all activities

I have an issue with my Android Studio project. In multipe activities I want to show AlertDialog after user click on back button, but now it means that I have to override onBackPressed() method seven times (in each activity). Is it possible to do that once for all activities?

Upvotes: 2

Views: 2075

Answers (4)

PeterMmm
PeterMmm

Reputation: 24630

I won't inherit from a "base class". Programming isn't always code reuse. And if, code reusing by inheritance is an anti pattern. As you will have seven onBackPressed() methods you will have seven onCreate() and so on. What you may do, is to create a class to have your onBackPressed logic to call from your seven onBackPressed() from every activity. Delegate common logic to a helper class.

Upvotes: 0

Kishan Maurya
Kishan Maurya

Reputation: 3394

Create abstract BaseActivity that will extends AppCompatActivity/Activity in this activity, override onBackPressed() , and create alertDialog

Now all activity will extent this BaseActivity only.

Upvotes: 0

Lev Leontev
Lev Leontev

Reputation: 2615

Create a single activity with onBackPressed overrided:

public class OnBackPressedActivity extends Activity {
    @Override
    public void onBackPressed() {
        // do stuff
    }
}

And then in your code use not extends Activity, but rather extends OnBackPressedActivity

Upvotes: 0

Ezio
Ezio

Reputation: 2985

You can have a BaseActivity and have your other activities extend from the BaseActivity. In the onBackPressed() method of activities, just call super.onBackPressed()

class BaseActivity extend AppCompatActivity {
     @Override public void onBackPressed() {
           //your logic here
     }
 }

class MainActivity extends BaseActivity {
     @Override public void onBackPressed() {
         super.onBackPressed()
     }
}

In this way, your actual logic will remain at one place. Keep in mind, that you have to override the onBackPressed method in each activity.

Upvotes: 3

Related Questions