Yawar
Yawar

Reputation: 1943

Implementing back button in android fragment activity

I'm using this tutorial to implement facebook login etc.

Facebook Login

I have added new fragment in this to show list of friends. Now when I press back button on my newly added fragment it takes me to the SPLASH fragment, I want same behaviour on back button on action bar. Means when I'm on my new fragment it shows me a back button on action bar. And pressing that back button takes me back to the SPLASH screen.

enter image description here

private void showFragment(int fragmentIndex, boolean addToBackStack) {
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    for (int i = 0; i < fragments.length; i++) {
        if (i == fragmentIndex) {
            transaction.show(fragments[i]);
        } else {
            transaction.hide(fragments[i]);
        }
    }
    if (addToBackStack) {
        transaction.addToBackStack(null);
    }
    transaction.commit();
}

Upvotes: 2

Views: 8884

Answers (1)

jaimin
jaimin

Reputation: 563

i got this code on stackoverflow after searching hard hope this may help you

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);// in on Create()

search for code onOptionsItemSelected(MenuItem item) and edit it in this way

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case android.R.id.home:
        // change your behaviour here
        Intent intent = new Intent(this, yourclass.class);// i started new activity here
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
  }
    return super.onOptionsItemSelected(item);
}

Upvotes: -1

Related Questions