Reputation: 5325
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.
Upvotes: 6
Views: 4005
Reputation: 1909
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
Upvotes: 2
Reputation: 1981
Handle onBackPressed event in Activity B
@Override
public void onBackPressed() {
super.onBackPressed();
finish(); // to close this activity
//finish() or start another activity
}
Upvotes: 0