To call the onBackPressed
method of the parent activity from a fragment in Android, you can use the getActivity
method of the fragment to get a reference to the parent activity, and then call the onBackPressed
method on that reference.
Here's an example of how you might do this in a fragment:
public class MyFragment extends Fragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { getActivity().onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }Source:wwttual.wuri.com
In this example, the onOptionsItemSelected
method is overridden to handle the back button press. If the back button is pressed, the onBackPressed
method of the parent activity is called using the getActivity
method.