The Wayback Machine - https://web.archive.org/web/20240808094504/https://www.geeksforgeeks.org/how-to-send-data-from-activity-to-fragment-in-android/
Open In App

How to Send Data From Activity to Fragment in Android?

Last Updated : 01 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Prerequisites:

In Android, a fragment is a portion of the user interface that can be used again and again. Fragment manages its own layout and has its own life cycle. Since fragment is a small portion of the bigger user interface, it can only be initialized inside an activity or another fragment. So if we wish to display any type of resources, such as a string, or an image inside the fragment, we will need to declare them in the activity and then pass it to the fragment. So in this article, we will show you how you can pass data from an Activity to the Fragment.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Create a custom fragment layout (my_custom_fragment.xml) in the layout folder

We shall pass a string to the fragment. To display this string, we implemented a TextView.

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- TextVIew to display the passed text -->
    <TextView
        android:id="@+id/fragmentTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="50sp"
        android:background="#0f9d58"/>

</LinearLayout>

Step 3: Add EditText, Button, and Frame in the layout file (activity_main.xml)

Refer to the comments inside the code for better understanding.

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- We will type text in this EditText -->
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="50sp"/>

    <!-- Click this button to pass text 
         in EditText to the Fragment -->
    <Button
        android:id="@+id/button"
        android:layout_below="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Pass"/>

    <!-- Text will be displayed in a
          TextView in this Fragment -->
    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_below="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Step 4: Create a class for the custom fragment (MyCustomFragment.kt)

This is a custom fragment class to inflate the custom layout in the frame layout present in the main activity.

Java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;

public class MyCustomFragment extends Fragment {
    // Declaring TextView from the custom fragment layout
    private TextView myTextView;

    // Override function when the view is being created
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState)
    {

        // Inflates the custom fragment layout
        View view = inflater.inflate(
            R.layout.my_custom_fragment, container, false);

        // Finds the TextView in the custom fragment
        myTextView = (TextView)view.findViewById(
            R.id.fragmentTextView);

        // Gets the data from the passed bundle
        Bundle bundle = getArguments();
        String message = bundle.getString("mText");

        // Sets the derived data (type String) in the
        // TextView
        myTextView.setText(message);

        return view;
    }
}
Kotlin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment

class MyCustomFragment: Fragment() {

    // Declaring TextView from the custom fragment layout
    private lateinit var myTextView: TextView

    // Override function when the view is being created
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

        // Inflates the custom fragment layout
        val view: View = inflater.inflate(R.layout.my_custom_fragment, container, false)

        // Finds the TextView in the custom fragment
        myTextView = view.findViewById<View>(R.id.fragmentTextView) as TextView

        // Gets the data from the passed bundle
        val bundle = arguments
        val message = bundle!!.getString("mText")

        // Sets the derived data (type String) in the TextView
        myTextView.text = message

        return view
    }
}

Step 5: Initialize MyCustomFragment class and pass the values from the EditText (MainActivity.kt)

In this program, the EditText value (input string) is fetched on a button click. The custom fragment class is initialized and the input string is passed to get desired results. Please refer to the comments inside the code below for a better understanding.

Java
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Declaring and initializing the EditText and
        // Button from the layout
        final EditText mEditText
            = findViewById(R.id.editText);
        final Button mButton = findViewById(R.id.button);

        // Declaring fragment manager from making data
        // transactions using the custom fragment
        final androidx.fragment.app
            .FragmentManager mFragmentManager
            = getSupportFragmentManager();
        final androidx.fragment.app
            .FragmentTransaction mFragmentTransaction
            = mFragmentManager.beginTransaction();
        final MyCustomFragment mFragment
            = new MyCustomFragment();

        // On button click, a bundle is initialized and the
        // text from the EditText is passed in the custom
        // fragment using this bundle
        mButton.setOnClickListener(
            new View.OnClickListener() {
                @Override public void onClick(View v)
                {
                    Bundle mBundle = new Bundle();
                    mBundle.putString(
                        "mText",
                        mEditText.getText().toString());
                    mFragment.setArguments(mBundle);
                    mFragmentTransaction
                        .add(R.id.frameLayout, mFragment)
                        .commit();
                }
            });
    }
}
Kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Declaring and initializing the EditText and Button from the layout
        val mEditText = findViewById<EditText>(R.id.editText)
        val mButton = findViewById<Button>(R.id.button)

        // Declaring fragment manager from making data
        // transactions using the custom fragment
        val mFragmentManager = supportFragmentManager
        val mFragmentTransaction = mFragmentManager.beginTransaction()
        val mFragment = MyCustomFragment()

        // On button click, a bundle is initialized and the 
        // text from the EditText is passed in the custom
        // fragment using this bundle
        mButton.setOnClickListener {
            val mBundle = Bundle()
            mBundle.putString("mText",mEditText.text.toString())
            mFragment.arguments = mBundle
            mFragmentTransaction.add(R.id.frameLayout, mFragment).commit()
        }
    }
}

Output:

We can see that when the text is typed in the EditText and the button is clicked, the same text is displayed in our custom fragment.



Similar Reads

How to Send Data From One Activity to Second Activity in Android?
This article aims to tell and show how to "Send the data from one activity to second activity using Intent". In this example, we have two activities, activity_first which are the source activity, and activity_second which is the destination activity. We can send the data using the putExtra() method from one activity and get the data from the second
7 min read
Fragment to Fragment Communication in Android using Shared ViewModel
If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it
6 min read
How to Pass Data from Dialog Fragment to Activity in Android?
In many applications, you may have seen that whenever we have to make choices some kind of elevated dialog box appears and ask the user for some input or choice. In this article, we are going to see the same that how we can pass data from a Dialog Box to activity in Android Studio. What we are going to build in this article?In this article, we will
4 min read
How to Send Image File from One Activity to Another Activity?
In this article, we are going to send an image from one activity to another. We will be using putExtra to send image and we will be using bundle to get the data sent from the previous activity and then we will be showing the received image. Step by Step Implementation Step 1: Create a New Project To create a new project in Android Studio please ref
3 min read
Difference Between a Fragment and an Activity in Android
An Activity is a user interface component that is mainly used to construct a single screen of the application and represents the main focus of attention on a screen. An activity can host one or more fragments at a time. Fragments, as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities. I
2 min read
How to Pass a Serializable Object from One Activity to Another Activity in Android?
While developing an application in Android, the developer can create more than one activity in the application. So, there can be many activities and can be a case to transfer data from one activity to the other. In such cases, Intents are used. Intents let the user jump from one activity to the other, or go from the current activity to the next act
4 min read
Send Multiple Data From One Activity to Another in Android using Kotlin
There are multiple ways for sending multiple data from one Activity to Another in Android, but in this article, we will do this using Bundle. Bundle in android is used to pass data from one activity to another, it takes data in key and value pairs. To understand this concept we will create a simple project in android studio using Kotlin. Step by St
3 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experie
4 min read
Dynamic Fragment in Android
Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments are more responsive and flexible than Static Fragme
4 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It has its own lifecycle and can receive input events a
12 min read
Article Tags :
three90RightbarBannerImg