How to perform a specific process when the back button is pressed in Android Fragment

Handle the back button (back key) of the terminal on the Fragment side and perform specific processing!

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

How to perform a specific process when the back button is pressed in Android Fragment
[Android] Easily control the event when the Back button is pressed in Fragment
[swift] How to control the behavior when the back button of NavigationBar is pressed
How to output the value when there is an array in the array
How to write the view when Vue is introduced in Rails?
[Ruby] How to prevent errors when nil is included in the operation
How to reference a column when overriding the column name method in ActiveRecord
How to set when "The constructor Empty () is not visible" occurs in junit
How far is the correct answer to divide the process?
[Android / Java] Set up a button to return to Fragment
[Rails] How to load JavaScript in a specific view
[Swift] Setting the behavior when the Share button is pressed
I want to go back to a specific VC by tapping the back button on the NavigationBar!
How to change the process depending on the list pressed when there are multiple ListViews
How to take a screenshot with the Android Studio emulator
How to set chrony when the time shifts in CentOS7
How to create a placeholder part to use in the IN clause
[Android] How to check if the Google Play developer service is installed when the app is launched
How to solve the problem when the value is not sent when the form is disabled in rails and sent
How to add the same Indexes in a nested array
[jOOQ] How to CASE WHEN in the WHERE / AND / OR clause
How to store the information entered in textarea in a variable in the method
How to identify the path that is easy to make a mistake
How to solve the unknown error when using slf4j in Java
[Android] I want to get the listener from the button in ListView
[Android] How to make Dialog Fragment
How to solve the problem that it is not processed normally when nesting beans in Spring Batch
How to set an image in the drawable Left / Right of a button using an icon font (Iconics)
What to do if Operation not permitted is displayed when you execute a command in the terminal
Change the processing when the button on RecyclerView is pressed for each list
Memo: [Java] If a file is in the monitored directory, process it.
How to get the current date as a string in yyyyMMdd format
[Docker] How to build when the source code is bind-mounted on the container
[Java small story] Monitor when a value is added to the List
[Java] How to get to the front of a specific string using the String class
How to find the total number of pages when paging in Java
How to constrain the action of the transition destination when not logged in
How to change the value of a variable at a breakpoint in intelliJ
How to pass a proxy when throwing REST over SSL in Java
How to get the absolute path of a directory running in Java
What to do if tomcat process remains when tomcat is stopped in eclipse
Android development, how to check null in the value of JSON object
Is it possible to put the library (aar) in the Android library (aar) and use it?
How to insert a video in Rails
Are you still exhausted by the sample video search? A button to send FANZA videos to Slack when pressed.
How to resolve the error'ActionView :: Template :: Error (The asset "application.css" is not present in the asset pipeline.'" When precompiling Rails assets
Android Easily give a "press" to a button
How to get the date in java
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
How to publish a library in jCenter
When reassigning to an argument in a Ruby method and then calling `super` → The reassigned one is used
How to use ExpandableListView in Android Studio
How to redirect to http-> https when SSL is enabled in Rails × Heroku environment
If the parameter is an array, how to include it in Stopara's params.permit
How to get the ID of a user authenticated with Firebase in Swift
How to check if an instance variable is defined in a Ruby class
How to fix a crash when deleting Realm data in Swift UI List
[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil
Androd: What to do about "The Realm is already in a write transaction in"
How to make a unique combination of data in the rails intermediate table
How to solve when you cannot connect to DB with a new container because the port is assigned to the existing docker container