Friday, March 2, 2018

android kotlin - LayoutInflater example

LayoutInflater
The LayoutInflater instantiates a layout XML file into its corresponding View objects. So with the LayoutInflater object, developers can include an XML View object in another XML layout programmatically. We also can add or update the included View’s widgets properties programmatically.

The following android development tutorial will demonstrate to us how we can use LayoutInflater to add an XML layout file programmatically inside another View. Developers can get the included layout file’s widgets references and can add or update their various properties such as they can set a text, can display an image, can change the colors and etc. Developers can define the included View’s position inside the container layout using constraints. They can define the child layout’s layout parameters also.

In this tutorial we created a custom layout XML file that has two Views, one is an ImageView and another is a TextView. We add this View to the container ViewGroup programmatically using LayoutInflater. At the including time we get the reference of both ImageView and TextView widgets. Then we add an image to the ImageView widget and set a text to the TextView widget. After doing this we attach the child View to the parent ViewGroup. Finally, our container View displays both Views contents inside its layout.

The LayoutInflater inflate() method inflates a new View hierarchy from the specified XML resource. This method takes three arguments which are resource, root, and attachToRoot. The ‘resource’ is the id for an XML layout resource to load. The ‘root’ is the parent ViewGroup. The method throws InflateException if there is an error.

This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to see how we use the LayoutInflater object to add an XML layout programmatically to a Container layout in an android application.

And how we updated the child XML layout widgets properties before adding it to the container layout in an application. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
import androidx.core.content.ContextCompat


class MainActivity : AppCompatActivity() {

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

        // Get the widgets reference from XML layout
        val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
        val tvTitle = findViewById<TextView>(R.id.tvTitle)

        // Get the LayoutInflater from Context
        val layoutInflater: LayoutInflater = LayoutInflater
            .from(applicationContext)

        // Inflate the layout using LayoutInflater
        val view: View = layoutInflater.inflate(
            R.layout.another_view, // Custom view/ layout
            rootLayout, // Root layout to attach the view
            false // Attach with root layout or not
        )

        // Find the text view from custom layout
        val label = view.findViewById<TextView>(R.id.tvLabel)

        // Get the ImageView widget reference from custom view
        val imageView = view.findViewById<ImageView>(R.id.imageView)

        // Set the text of custom view's text view widget
        label.text = "Cute Flower."

        // Set an image to image view widget
        imageView.setImageDrawable(
            ContextCompat.getDrawable(
                applicationContext,R.drawable.flower4)
        )

        // Initialize a ConstraintLayout LayoutParams instance
        val layoutParams = LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT
        )

        // Set the inflated view's position on container view
        layoutParams.topToBottom = tvTitle.id

        // Set the layout params of inflated view
        view.layoutParams = layoutParams

        // Finally, add the view/custom layout to the activity root layout
        rootLayout.addView(view,0)
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Android!"
        android:fontFamily="sans-serif"
        android:textSize="28sp"
        android:padding="12dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
another_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="350dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="16dp"
        android:padding="8dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples