Yash
Yash

Reputation: 5325

Need to press back button twice to navigate back from activity

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,

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

Answers (3)

Christophe Blin
Christophe Blin

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

Sabari
Sabari

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

Manu
Manu

Reputation: 182

Maybe just override the onBackPressed method.

@Override
public void onBackPressed() {
   finish();
}

also keep in mind the BackStack

Upvotes: 0

Related Questions