Physical Android Back Button does not respond when coming from a selected list item

My app has quite a few separate activity/fragment pairs, and relies on the Android universal back button for much of its navigation. This button works fine, EXCEPT when I'm trying to return from a DetailView activity back to a list of search results. Here's what the search results code looks like:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {

View v = inflater.inflate(R.layout.results_fragment, container, false);

ListView lv;
lv = (ListView)v.findViewById(R.id.listViewResults);
lv.setAdapter(SearchResultsAdapter);
lv.setEmptyView(v.findViewById(R.id.emptyElement));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
        ItemType selectedItem;
        selectedItem = (ItemType)adapter.getItemAtPosition(position);
        Intent i = new Intent(getActivity(), DetailViewActivity.class);
        i.putExtra(DetailViewFragment.RESULT_ID, resultIdNumber);
        startActivity(i);
    }
});

// ... some other stuff

   return v;
}

The DetailView is simply a collection of images and text.

The search returns expected results, and selecting the item shows the correct DetailViewFragment.

It seems like a very typical architecture, so I'm not sure why navigation back to the results page should be so problematic. I tried setting breakpoints to determine if the results activity ever restarted, but apparently it did not.

1 answer

  • answered 2018-11-08 03:22 Alejandro Cumpa

    If you want to make something when the back button is pressed, you have to override it:

    @Override
    public void onBackPressed()
    {
         // code here 
        finish(); // to end activity: 
    }