0

I have two activities.One of them has Fragment.
From this fragment I can go to another activity, but by clicking the button "home" it goes to previous activity instead of going to the fragment of the previous activity.

Image

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_closet);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
Mika Dior
  • 53
  • 8
  • Check this http://stackoverflow.com/questions/13086840/actionbar-up-navigation-with-fragments – Vardan95 Jan 10 '17 at 18:05
  • Possible duplicate of [actionbar up navigation with fragments](http://stackoverflow.com/questions/13086840/actionbar-up-navigation-with-fragments) – Vardan95 Jan 10 '17 at 18:06

4 Answers4

2

Refere below code :

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        finish();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}
samsad
  • 1,241
  • 1
  • 10
  • 15
1

You need to override below method :

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()== android.R.id.home) {
            finish();
            return true;
        }
        return false;
    }
0
getSupportActionBar().setNavigationOnClickListener(new OnClickListener {
    public void onClick(View v){
      onBackPressed()
    }
})
Tomasz Czura
  • 2,414
  • 1
  • 14
  • 18
0

Since you want same behavior as of back button you should use onBackPressed();

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
Nilesh Deokar
  • 2,975
  • 30
  • 53