How to Send Data From Activity to Fragment in Android?
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
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical" >
< 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
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< EditText
android:id = "@+id/editText"
android:layout_width = "match_parent"
android:layout_height = "50sp" />
< 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" />
< 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.
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() {
private lateinit var myTextView: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view: View = inflater.inflate(R.layout.my_custom_fragment, container, false )
myTextView = view.findViewById<View>(R.id.fragmentTextView) as TextView
val bundle = arguments
val message = bundle!!.getString( "mText" )
myTextView.text = message
return view
}
}
|
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 {
private TextView myTextView;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(
R.layout.my_custom_fragment, container, false );
myTextView = (TextView)view.findViewById(
R.id.fragmentTextView);
Bundle bundle = getArguments();
String message = bundle.getString( "mText" );
myTextView.setText(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.
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)
val mEditText = findViewById<EditText>(R.id.editText)
val mButton = findViewById<Button>(R.id.button)
val mFragmentManager = supportFragmentManager
val mFragmentTransaction = mFragmentManager.beginTransaction()
val mFragment = MyCustomFragment()
mButton.setOnClickListener {
val mBundle = Bundle()
mBundle.putString( "mText" ,mEditText.text.toString())
mFragment.arguments = mBundle
mFragmentTransaction.add(R.id.frameLayout, mFragment).commit()
}
}
}
|
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);
final EditText mEditText
= findViewById(R.id.editText);
final Button mButton = findViewById(R.id.button);
final androidx.fragment.app
.FragmentManager mFragmentManager
= getSupportFragmentManager();
final androidx.fragment.app
.FragmentTransaction mFragmentTransaction
= mFragmentManager.beginTransaction();
final MyCustomFragment mFragment
= new MyCustomFragment();
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();
}
});
}
}
|
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.
Last Updated :
17 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...