You must double-click the "Back" button to switch from activity

I have the main action A (PlacesListActivity). It calls activity B (AboutMeActivity) from the navigation box. I declared activity A as the parent activity of B in the manifest.

Now when I go from A-> B,

  • if I click on the back arrow in the action bar, it returns me to activity A.

  • regarding the hardware button, I have to press it twice to return to activity A. When I press the hardware once, nothing happens. It seems to be just restarting activity B. I don't want this. A single push of a hardware button should complete the task.

Code for action 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); ..... } 

The initialization function only initializes some user interface elements.

Code for invoking operation B:

 @Override public void onDrawerItemSelected(View view, int position) { Intent i; switch (position) { case 0: i = new Intent(this, AboutMeActivity.class); startActivity(i); break; ...... 

Manifesto:

 <activity android:name="....AboutMeActivity" android:parentActivityName="....PlacesListActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="....PlacesListActivity" /> </activity> 

Edit:

I tried overriding OnBackPressed() , but it is never called.

tried overriding OnKeyDown() and called finish() on it, but still I have to click it twice to return to activity A.

+5
source share
3 answers

In my case, the search component had focus when I press the hardware return button

By performing this problem, I solved:

 override fun onResume() { super.onResume() searchInputView?.clearFocus() //searchInputView is initialized in onCreateOptionsMenu } 

As a general rule, make sure the back button matches the activity value, not the subcomponent of your activity.

+1
source

Maybe just override the onBackPressed method.

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

also remember backstack

0
source

Handle onBackPressed event in Activity B

  @Override public void onBackPressed() { super.onBackPressed(); finish(); // to close this activity //finish() or start another activity } 
0
source

Source: https://habr.com/ru/post/1243457/


All Articles