Home » Android » Actionbar back button not working in android

Actionbar back button not working in android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am creating a android app where i need to put back navigation ,so that when user click on action bar’s home button user should be moved to one screen back on my app.But action bar home button is not responding to click events.
Here is my code.

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }
            @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);

        ActionBar actionBar = getActivity().getActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);


        return rootView;
    } }

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.home:
        Toast.makeText(getApplication(), "Back", Toast.LENGTH_LONG).show();

        break;

    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}
How to&Answers:
case android.R.id.home:

try to use this instead of case R.id.home:

Answer:

Use android.R.id.home instead of R.id.home

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        Toast.makeText(getApplication(), "Back", Toast.LENGTH_LONG).show();

        break;

    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}