Mr. Thanks a lot
Mr. Thanks a lot

Reputation: 235

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?

Upvotes: 1

Views: 3295

Answers (2)

Sree Reddy Menon
Sree Reddy Menon

Reputation: 1311

if you want actionbar menu on fragment then

override onCreateOptionsMenu on your fragment. and clear the menu of activity

    @Override
            public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
                super.onCreateOptionsMenu(menu, inflater);
        menu.clear();

//if you dont have options skip inflate 
                    inflater.inflate(R.menu.menu_second, menu);
            }

and

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {

          int id = item.getItemId();
            if (id == android.R.id.home) {
            Toast.makeText(getActivity().getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
        return true;
    }


return super.onOptionsItemSelected(item);
}

Upvotes: 0

Inducesmile
Inducesmile

Reputation: 2493

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);
}

Upvotes: 2

Related Questions