Tuesday, February 13, 2018

How to add Fragment in Activity - Kotlin

Today we are going to see how to add fragment in activity dynamically using kotlin
Kotlin is statically types programming language and can be run on jvm and JavaScript.

Since Android Studio 3.0 Kotlin is fully supported

Some Bits of Kotlin.


1. Variables in kotlin are immutable declared as val
val arg : String="Immutable"
And mutable variables declared as var
var sum : Int
         sum=5 +5

2. Semicolon in kotlin is optional

Now lets see in step by step approach of how to add fragment to the activity.

Step 1: Start Android Studio 3.0.1 or latest

Start new  "Android Studio Project" Enter Project name as "FragmentInKotlin" change package name
Make sure to check "Include kotlin support" Click next

Step 2: Do not add any Activity

We will create our activity and fragments by ourself, Click next and Finish.


Step 3: Create MainActivity by adding new kotlin class

Once project is opened in  Android Studio right click on your package choose new kotlin class
Enter name as "MainActivity" as below


Step 4: Create main.xml layout for main activity

As below or copy below code



<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/container" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools" tools:context="com.droidtech.fragmentinkotlin.MainActivity"> </LinearLayout>


Here we have added id to our layout as it is going to behave as container of our Fragment.
Now set this layout to our MainActivity.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // set main.xml as view    setContentView(R.layout.main)
} 

Step 5: Create Fragment and layout of Fragment
To add fragment step 3 will be same.

Create MainFragment as follow.                   
Now you must have some basic syntax of kotlin.

class MainFragment : Fragment() {

    var mParam: String? = null    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null)
            mParam = arguments.getString(ARG_PARAM)

    }
   

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater!!.inflate(R.layout.fragment_main, container, false)

        val button = view.findViewById<Button>(R.id.button)
        button.setOnClickListener  { mListener!!.onInteractionHappened("button Clicked") }        return view
    }

    companion object {

        val ARG_PARAM: String = "param"
        fun neInstance(param: String): MainFragment {
            val fragment = MainFragment()
            val args = Bundle()
            args.putString(ARG_PARAM, param)
            fragment.arguments = args
            return fragment
        }
    }

Now Create fragment_main.xml in layout folder as below.


<?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:orientation="vertical">

  <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"     
    android:gravity="center" android:text="@string/label_welcome" 
    android:textColor="@color/colorAccent" android:textSize="20dp" />

 <Button android:onClick="onClick" android:layout_marginTop="20dp" android:id="@+id/button" 
    android:layout_width="match_parent" android:layout_height="wrap_content" 
    android:text="Button" />

 </LinearLayout>


 Step 6: Add fragment to our MainActivity

As below.
// Now add this MainFragment to contaner layoutval fragment = MainFragment.neInstance("Main Fragment")
val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
ft.add(R.id.container, fragment, "MAINFRAGMENT")
ft.commit()
Step 7: Manifest entry of MainActivity

We have added our fragment to MainActivity now add MianActivity entry to manifest.xml file as below.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.droidtech.fragmentinkotlin">

   <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" android:configChanges="orientation|keyboardHidden" 
     android:launchMode="standard"> 

<intent-filter>
         <action android:name="android.intent.action.MAIN" /> 
<category   android:name="android.intent.category.LAUNCHER" /> 
</intent-filter>

 </activity>

 </application>

 </manifest>Step 8: Interface in fragment for callback from interface to acivity.

In kotlin interface creation is similar to java as

interface OnMainFragmentInteractionListener {
    fun onInteractionHappened(arg: String)
}

Declare interface as
var mListener: OnMainFragmentInteractionListener? = null

we have declared interface object as var because at time of declaration we don't know it's value later we will assign to it so it makes it mutable.

override fun onAttach(context: Context?) {
    super.onAttach(context)
    if (context is OnMainFragmentInteractionListener) {
        mListener = context
    } else {
        throw ClassCastException(context.toString() +
            " must implement OnMainFragmentInteractionListener")
    }
}                                                          
 Now activity must implement this interface as below full code for mainActivity is as below.

package com.droidtech.fragmentinkotlin

import android.os.Bundle
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import android.widget.Toast

/** * Created by Jayesh on 2/12/2018. */class MainActivity : AppCompatActivity(), MainFragment.OnMainFragmentInteractionListener {
    override fun onInteractionHappened(arg: String) {
        Toast.makeText(baseContext, "event fired" + arg, Toast.LENGTH_SHORT).show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // set main.xml as view        setContentView(R.layout.main)
        // Now add this MainFragment to contaner layout        val fragment = MainFragment.neInstance("Main Fragment")
        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        ft.add(R.id.container, fragment, "MAINFRAGMENT")
        ft.commit()

    }

    override fun onRestart() {
        super.onRestart()
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onStop() {
        super.onStop()
    }


    override fun onDestroy() {
        super.onDestroy()
    }

}


Build and run your project.

Stay cool have beers.

No comments:

Post a Comment