Skip to main content

Fragments In Android Kotlin

  • Fragments Represent Reusable portion of your apps UI
  •  Fragments are used to define and manage UI of a single screen or portion of screen.
  • Fragments has it's own layout , Life cycle and can handle input events
  • Fragments can not exist on its own it must be hosted by an Activity or another Fragment


Activities act as a frame that contains the fragment .Each fragment operates like a view in the activity but it has 
has it's own layout , Life cycle and can handle input events.
Activities are ideal place to put global elements around your app's UI like Navigation Drawer, Toolbar , Bottom Navigation and fragments are better suited to define UI of single screen or portion of screen. You can use multiple Fragments with single Activity ,  this gives more modularity and reusability to our code.


Add the following dependency in your app level build.gradle file to use fragments
implementation "androidx.fragment:fragment-ktx:1.3.6"
Now create a new fragment 
package com.arun.androidtutsforu.demofragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class DemoFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_demo, container, false)
    }
}
This is the layout of our fragment
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DemoFragment">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a Fragment"
        android:textColor="#000000"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
 Fragment can not exists on its own , it must be hosted by an Activity or another Fragment.
Add  Fragment to the Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
   <fragment
       android:id="@+id/demofragment"
       android:name="com.arun.androidtutsforu.demofragment.DemoFragment"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
</LinearLayout>
android:name="com.arun.androidtutsforu.demofragment.DemoFragment" --This should be fully-qualified  class name of the fragment
Following is the  MainActivity
package com.arun.androidtutsforu.demofragment
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Comments

Popular posts

Android Sqlite and ListView Example

This is simple application which insert data into Sqlite database --and shows the data  from the database in a ListView ListView is not used in android Anymore . We use RecyclerView and CardView   in Android RecyclerView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html RecyclerView with CardView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html This  is the first Activity of application which shows data from database in listview. Register here buton will start a Registration Activity. Submit button will add data to database and show it in the ListView of MainActivity. Update can be performed by clicking ListView items.     you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdS0dtT1R2TXdBWEE&usp=sharing click on the abov...

Cannot Choose Between Multiple Debugging Devices in Android Studio

If  you connect multiple Devices or Emulators to Android Studio and Run Application. Application will only run on the first run device.  It will not ask to select connected device. ie, 1. If you connect one Device or Emulator 2. Run a project on the device or Emulator 3. Connect another Device or start another Emulator 4. Try to run project on new device 5. It will only run on first device  . will not ask to select Connected Device or Emulators 6. Select Deployment Target Dialog box will not show. If this Problem occurs to you while Developing on android Studio .  First thing to do is to Stop Application after running on the first device This can be done by clicking Stop app icon which is left of the AVD manger icon. Or by using Keyboard shortcut CTRL+F2 Now if you Run the project , Select Deployment Target Dialog box will pop up. You can select another Device or emulator from the list If still Select Deployment Target window not showing up an...

ViewModel with Jetpack Compose

  Compose uses remember API to store object in memory. Stored value is returned during recomposition . remember helps us retain data across recompostion , but when configuration changes happen all stored values are lost . One way to overcome this is to use rememberSaveable . rememberSaveable saves any value that can be saved in a Bundle , so it will survive configuration changes.  But when we are using lot of data , for example a list we can cannot use a rememberSavble beacuse there is limit on amount of data that can be stored in Bundle . So we use ViweModel . ViewModel provide the ui state and access to the business logic located in other layers of the app. It also survives configuration changes. ViewModel handles events coming from the UI or other layers of the app and updates the state holder based on the events. We need to add the following dependency in our app level build.gradle to use ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1" F...