1

I have an app which has multiple activities. One example would be my MainActivity which displays a list of items from where you can open a "detail" overview of certain item.

Once click an item to open it I open another activity like this

final Intent intent = new Intent(getApplicationContext(), AddActivity.class);
getApplicationContext().startActivity(intent);

Once the activity is opened in its toolbar I have a back button. I guess that button comes out of the box since I am using android.support.v7.widget.Toolbar.

In case where on MainActivity I have scrolled far in the list and then decide to open a new activity and on that new activity I click toolbar back button I am returned to MainActivity but its refreshed (its OnCreate method gets called).

In case where I open second activity and it has a button that performs some action and at the end returns you to MainActivity calling onBackPressed() from FragmentActivity that is extended (by extending AppCompatActivity), it would return you to MainActivity but without any refreshing you would be able to continue where you stopped.

My question is if it is possible to replace current behavior of toolbar back button with this onBackPressed() behavior?

mirzak
  • 1,043
  • 4
  • 15
  • 30
  • i see you are using application level context to start activity rather then MainActivity context, any reason ? – Sahil Nov 10 '18 at 07:20
  • Not really. I am just starting with android so I dont really know the difference between them. – mirzak Nov 10 '18 at 07:21
  • 1
    no prob, there is difference and you should be using activity's context, go through https://stackoverflow.com/a/10347346/5906447. Second, dont depend on oncreate() method to refresh your activity, you may use onResume() lifecycle method if you need to refresh acitivity data. Forcing activity to recreate is an expensive operation. – Sahil Nov 10 '18 at 07:27
  • Yes, that is exactly the thing, I do not want to call onCreate if I go back using toolbar button. Is it possible to override its function ? – mirzak Nov 10 '18 at 07:44
  • I would guess that toolbar back and hard back button call different methods – mirzak Nov 10 '18 at 07:47

2 Answers2

0

I have made it work. All I needed to do was to override onSupportNavigateUp in order to get same behavior on both buttons.

@Override
public boolean onSupportNavigateUp() {
    onBackPressed(); // one inherited from android.support.v4.app.FragmentActivity

    return false;
}
mirzak
  • 1,043
  • 4
  • 15
  • 30
0

Simply u can override the onbackPressed method and call that method when toolbars back button clicked.

@Override
public void onBackPressed() {
   super.onBackPressed()
}

call this when that button clicked.

PushpikaWan
  • 2,437
  • 3
  • 14
  • 23