How to transfer a variable from fragment to activity in Android?

A story about how in Android to transfer information from a fragment (Fragment) to an activity (Activity). The information will be useful for beginners (juniors), who master programming for Android, and are unlikely to be interesting for middles and seniors.

Launch the IDE (integrated development environment) Android Studio . Create a new project: File -> New -> New Project. Select "Empty Activity", click "Next".



Fill in the fields “Name”, “Package name”, “Save location”.



The IDE will automatically create two files: “MainActivity.java” in the “java / [package name]” directory, “activity_main.xml” in the “res / layout” directory.





Java file determines what the application does , xml - how it looks. It does so far very little, only "setContentView (R.layout.activity_main);". This line tells the application to use the activity_main.xml layout at startup. And, since the layout contains only one widget of the “TextView” type with the text “Hello World!”, Our application also looks very modest.



In the project folder, create a fragment with the name "Fragment1".





The IDE will create two files: “Fragment1” and “fragment_fragment1.xml”.





Open the fragment layout file and delete the “TextView” widget we don’t need with a welcome line.



Switch to design mode and drag the (Button) button onto the layout.



The IDE will create a button with the identifier "button1".



Now edit the layout of the main activity, i.e. file "activity_main.xml"



Move the text widget higher and add the fragment we created to the layout (to do this, drag the "<>" element onto the layout, select "Fragment1" and click "OK").



In the activity layout in the fragment settings, set layout_height = “wrap_content” and edit its placement to your taste. We will also change the identifier of the text field to “textReport”, and the fragment to “fragmentWithButton”.



Run the emulator (Shift + F10) and see what happened.



The application displays the inscription "Hello World!" and the BUTTON button. The inscription is deduced from activity , the button belongs to a fragment . The button is pressed, but so far it has no effect. Let's try to program the inscription to display the number of button presses. For this we will needsend a message about a button click from a fragment to activity .

First, we will teach the fragment to count the number of button clicks. Open the file “Fragment1.java”.



Add the variable "counter". In the “onCreateView” method, which is called immediately after the fragment is created, create the button “listener”. The IDE will require the implementation of View.OnClickListener - agree (Alt + Enter). Let's create (redefine) the onClick method, which will increase the value of the “counter” variable with each click of the button and display a pop-up message.



Let's check in the emulator (again Shift + F10) how it works. Pressing the button will cause the pop-up message “Number of button clicks: ...” to appear at the bottom of the application screen.



Great, move on. Our main goal is to transfer information (in this case, the number of button clicks) from the fragment instance to the activity instance. Alas, the life cycles of activities and fragments are organized so that Android (almost) does not allow activity and a fragment to communicate directly, so we need an intermediary interface. Let's call him “Postman” (postman). The interface can be created either in a separate file or in a file with a fragment code; we will choose the first option. Our Postman interface will contain a single abstract (without a "body") method of "fragmentMail".



We will use the variable "numberOfClicks" as an "envelope" to transfer messages from the fragment to activity.

Open the file with the activity code "MainActivity.java". As we recall, it looks like this: We



implement the Postman interface and add the fragmentMail interface method to the activity, overriding it ( Override ).



Now, as soon as the activity "sees" a new value in the variable "numberOfClicks", it will display an updated message in the textReport text field.

But we still need to “put the letter in the envelope”, i.e. pass to the variable the number of clicks on the button. And we do this in the fragment code. Open the file "Fragment1.java".

D̶o̶b̶a̶v̶l̶ya̶e̶m̶ ̶v̶ ̶p̶o̶d̶p̶i̶s̶̶ ̶k̶l̶a̶s̶s̶a̶ ̶i̶m̶p̶l̶e̶m̶e̶n̶t̶a̶ts̶i̶yu̶ ̶i̶n̶t̶e̶r̶f̶e̶y̶s̶a̶ ̶ «̶P̶o̶s̶t̶m̶a̶n̶» ̶.̶ ̶I̶D̶E̶ ̶p̶o̶t̶r̶e̶b̶u̶e̶t̶ ̶p̶e̶r̶e̶o̶p̶r̶e̶d̶e̶l̶i̶t̶̶ ̶m̶e̶t̶o̶d̶ ̶i̶n̶t̶e̶r̶f̶e̶y̶s̶a̶ ̶ «̶f̶r̶a̶g̶m̶e̶n̶t̶M̶a̶i̶l̶» ̶, ̶ ̶n̶o̶ ̶d̶e̶l̶a̶t̶̶ ̶v̶ ̶n̶o̶m̶ ̶m̶y̶ ̶n̶i̶ch̶e̶g̶o̶ ̶n̶e̶ ̶b̶u̶d̶e̶m̶, ̶ ̶p̶o̶e̶t̶o̶m̶u̶ ̶o̶s̶t̶a̶v̶i̶m̶ ̶e̶g̶o̶ ̶t̶e̶l̶o̶ ̶p̶u̶s̶t̶y̶m̶. [Deleted, see “Note 1 of 04/20/2019”]

We will need a link to an activity instance. We will receive it when attaching a fragment to an activity like this:


In the “onClick” method (the same one that is called when our button is clicked), we will add a call to the interface from an activity instance.



The final code of the fragment after deleting (for compactness) comments looks like this:


Now ourthe fragment counts the number of button clicks , displays them in a pop-up message, and then, using the Postman interface, passes the value of the counter variable to the variable numberOfClicks , which serves as an envelope container for sending messages from the fragment to activity. Activity, receiving a new message, immediately displays it in its widget text field with the identifier "textReport". The goal is achieved!


PS: Changing the programming language from Java to Kotlin can significantly reduce the code for the fragment:



PPS: You can download the project files here: Java , Kotlin .

Note 1 from 04/20/2019:


The implementation of the Postman interface has been removed from the fragment code.
A fragment works with an interface through activity in which this interface is already implemented.
Thanks to mikaakim for commenting .
Updated files can be downloaded from github at the links above.

Also popular now: