Initially I wanted to control the back button on the Fragment side, but since it is necessary to override onBackPressed () in Activity and control it, I was able to implement and operate as follows.
The rough flow is as follows
--Override the process when the back button is pressed in Activity --Tell the button press event to return from Activity to Fragment through Interface --Inherit Interface on Fragment side and implement specific processing
First, add the following to the original Activity
@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("handlingBackPressed");
if (fragment instanceof OnBackKeyPressedListener) {
((OnBackKeyPressedListener) fragment).onBackPressed();
}
super.onBackPressed();
}
Give findFragmentByTag an appropriate name. Here, "handling BackPressed" is used.
Then create the interface OnBackKeyPressedListener.java
public interface OnBackKeyPressedListener {
void onBackPressed();
}
Next, add the "handlingBackPressed" tag when generating the Fragment you want to control the back button.
fragment = new HogeFragment();
manager.beginTransaction().replace(R.id.main_area_layout, fragment, "handlingBackPressed").addToBackStack(null).commit();
Inherit the interface created by HogeFragment and add a specific process in onBackPressed ()
public class FavoriteItemListFragment implements OnBackKeyPressedListener {
・ ・ ・ ・
@Override
public void onBackPressed() {
//Handles back key events and describes necessary processing.
//For example, display the text in the Toolbar area controlled by Activity.
TextView leftToolbarText = mContext.findViewById(R.id.tool_bar_left_text);
leftToolbarText.setVisibility(View.VISIBLE);
}
that's all!
Recommended Posts