Send data from one Fragment to another using Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to send data from one Fragment to another using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/relativeLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="8dp">
</RelativeLayout>

Step 3 − Create two FragmentActivity and add the codes which are given below.

fragmentOne.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="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   android:padding="8dp">
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="50dp"
      android:hint="Enter your message"
      android:textColorHint="@android:color/background_dark"
      android:textSize="16sp"
      android:textStyle="bold" />
   <Button
      android:id="@+id/btnSend"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@android:color/holo_blue_dark"
      android:padding="10dp"
      android:text="Send Message"
      android:textColor="@android:color/white"
      android:textStyle="bold" />
</LinearLayout>

FirstFragment.kt

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_one.view.*
class FirstFragment : Fragment() {
   private lateinit var communicator: Communicator
   override fun onCreateView(
      inflater: LayoutInflater,
      container: ViewGroup?,
      savedInstanceState: Bundle?
   ): View? {
      val rootView = inflater.inflate(R.layout.fragment_one, container, false) as ViewGroup
      communicator = activity as Communicator
      rootView.btnSend.setOnClickListener {
         communicator.passData(rootView.editText.text.toString())
      }
      return rootView
   }
}

fragmentTwo.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="match_parent"
   android:gravity="center"
   android:orientation="vertical">
   <TextView
      android:id="@+id/outPutTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:textColor="@android:color/background_dark"
      android:textSize="24sp"
      android:textStyle="bold" />
</LinearLayout>

FragmentTwo.kt

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_two.view.*
class FragmentTwo : Fragment() {
   var inputText: String? = ""
   override fun onCreateView(
      inflater: LayoutInflater,
      container: ViewGroup?,
      savedInstanceState: Bundle?
   ): View? {
      val rootView = inflater.inflate(R.layout.fragment_two, container, false)
      inputText = arguments?.getString("inputText")
      rootView.outPutTextView.text = inputText
      return rootView
   }
}

Step 4 − Add the following code to src/MainActivity.kt

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
class MainActivity : AppCompatActivity(), Communicator {
   public override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      val firstFragment = FirstFragment()
      supportFragmentManager.beginTransaction().replace(R.id.relativeLayout, firstFragment)
      .commit()
   }
   override fun passData(editTextInput: String) {
      val bundle = Bundle()
      bundle.putString("inputText", editTextInput)
      val transaction = this.supportFragmentManager.beginTransaction()
      val fragmentTwo = FragmentTwo()
      fragmentTwo.arguments = bundle
      transaction.replace(R.id.relativeLayout, fragmentTwo)
      transaction.addToBackStack(null)
      transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
      transaction.commit()
   }
}

Step 5 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" /&g;
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter&g;
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 20-Apr-2020 16:56:47
Advertisements