Search code examples
androidandroid-fragmentsandroid-actionbar

onOptionsItemSelected not being called when Back button is pressed on actionBar


As simple as that, when I press the back button nothing happens. Here is the code Im running:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tm_activity_inicio_resumen, container, false);

    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_left2);

    return view;
}

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Toast.makeText(getActivity().getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}

Is something wrong with this implementation?


Solution

  • Change to this code.

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