I have a main activity A (PlacesListActivity). It calls activity B (AboutMeActivity) from the navigation drawer. I have declared activity A as the parent activity of B in manifest.
Now, when I go from A->B,
if i press the back arrow in action bar, it takes me back to the activity A.
regarding the hardware button, I have to press it twice to go back to activity A. When I press hardware back once, nothing happens. It seems like it just reloads activity B. I don't want this. Pressing hardware button once should do the job.
Code for activity B :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_me);
initialize();
}
private void initialize() {
toolbar = (Toolbar) findViewById(R.id.toolbarAboutMe);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
.....
}
initialize function just initializes some UI elements.
Code for calling activity B :
@Override
public void onDrawerItemSelected(View view, int position) {
Intent i;
switch (position) {
case 0:
i = new Intent(this, AboutMeActivity.class);
startActivity(i);
break;
......
Manifest :
<activity
android:name="....AboutMeActivity"
android:parentActivityName="....PlacesListActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="....PlacesListActivity" />
</activity>
Edit :
I have tried with overriding OnBackPressed()
, but it never gets called.
tried with overriding OnKeyDown()
and calling finish()
in that, but still, I have to press it twice to go back to activity A.
Once you press the back key the activity's onDestroy() method will be called and the activity will be flushed out of the memory. You will then be required to restart the activity by calling the startActivity() method which will in turn call its onCreate() Method.
Depending on the user's Android device, this button might be a physical button or a software button. Android maintains a back stack of destinations as the user navigates throughout your application. This usually allows Android to properly navigate to previous destinations when the Back button is pressed.
In my case, the search component did have the focus when I press the hardware back button
Doing this solved my problem :
override fun onResume() {
super.onResume()
searchInputView?.clearFocus() //searchInputView is initialized in onCreateOptionsMenu
}
So generally speaking, be sure that the back button is correclty catched by the activity and not by a subcomponent of your activity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With