Carasel
Carasel

Reputation: 2871

Going back to the previous activity and fragment from an additional back button

I have an app with tab navigation between fragments. One of these fragments has an option to open a new activity. When I use the built in device back button from this activity it goes back to the tabbed activity with the previous fragment tab selected.

I have added a back button to the action bar of an activity in my app by using:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and setting the parent activity in the manifest, but this button always navigates back to the first tab of the parent activity, rather than the one that was previously visible.

How can I make this back button behave in the same way as the device back button?

Upvotes: 2

Views: 2594

Answers (2)

H Raval
H Raval

Reputation: 1903

Handle back event in this manner

    @Override 
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch(id) {
        case android.R.id.home:
            onBackPressed(); 
            return true; 
    } 
    return super.onOptionsItemSelected(item);
}

in back press method

 @Override 
    public void onBackPressed() { 
     Intent intent = new Intent(SecondActivity.this,TabbedActivity.class);
    intent.putExtra("IsBack",true);
    startActivity(intent);
}

in your tabbed activity

   protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_tabs);

          if(getIntent().getExtras().getBoolean("IsBack")){
             //navigate to your desire fragment
       }
    }

Upvotes: 0

activesince93
activesince93

Reputation: 1736

Do something like this:

@Override 
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch(id) {
        case android.R.id.home:
            onBackPressed(); 
            return true; 
    } 
    return super.onOptionsItemSelected(item);
} 

onBackPressed() method:

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

Upvotes: 6

Related Questions