android kotlin - Add a hint to spinner example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this

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

        // list of spinner items
        val list = mutableListOf(
            "Amaranth purple",
            "Black olive",
            "Asparagus",
            "Android green",
            "Blue sapphire"
        )

        // add a hint to spinner
        // list first item will show as hint
        list.add(0,"Select favorite color")

        // initialize an array adapter for spinner
        val adapter:ArrayAdapter<String> = object: ArrayAdapter<String>(
            context,
            android.R.layout.simple_spinner_dropdown_item,
            list
        ){
            override fun getDropDownView(
                position: Int,
                convertView: View?,
                parent: ViewGroup
            ): View {
                val view:TextView = super.getDropDownView(
                    position,
                    convertView,
                    parent
                ) as TextView
                // set item text bold
                view.setTypeface(view.typeface, Typeface.BOLD)

                // set item padding
                view.setPadding(64,0,128,0)

                // set selected item style
                if (position == spinner.selectedItemPosition
                    && position !=0 ){
                    view.background = ColorDrawable(
                        Color.parseColor("#F8F8F8"))
                    view.setTextColor(
                        Color.parseColor("#0018A8"))
                }

                // make hint item color gray
                if(position == 0){
                    view.setTextColor(Color.LTGRAY)
                }

                return view
            }

            override fun isEnabled(position: Int): Boolean {
                // disable first item
                // first item is display as hint
                return position != 0
            }
        }

        // finally, data bind spinner with adapter
        spinner.adapter = adapter


        // spinner on item selected listener
        spinner.onItemSelectedListener = object
            : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                // by default spinner initial selected item is first item
                if (position != 0){
                    textView.text = "Selected : "
                    // get selected item text
                    textView.append(
                        parent.getItemAtPosition(position).toString()
                    )
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // another interface callback
            }
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Spinner onItemSelectedListener example

Spinner onItemSelectedListener
The Spinner provides an easy way to select an item from a list. The Spinner always shows its currently selected item only. Other items remain invisible and users can see them when they click on the Spinner itself. On Spinner click, it displays a drop-down menu with all other available items. So, the user can select an item from all of the available items.

The following android application development tutorial will demonstrate to us how we can set an item selected listener for the Spinner widget. The Spinner AdapterView OnItemSelectedListener registers a callback to invoke when an item in this AdapterView has been selected. So developer gets the Spinner selected value immediately when the user selects it or changes their selection.

To populate a Spinner widget with items we have to create an item list. Then we create an instance of ArrayAdapter with this list. After that, we bind the Spinner widget with this ArrayAdapter. So the Spinner widget display items from the list.

Finally, we set the Spinner onItemSelectedListener value to an ArrayAdapter.OnItemSelectedListener. AdapterView OnItemSelectedListener interface onItemSelected() method allows us to get the user-selected item details in real-time and programmatically. So when the user selects an item from the Spinner widget developers can get this selected item’s details and can perform related tasks.

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 can use Spinner OnItemSelectedListener in an android application.

And how we can get the Spinner selected item details programmatically in real-time when users select an item or change their selection 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.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this;

        // Get the widgets reference from XML layout
        val spinner = findViewById<Spinner>(R.id.spinner)
        val textView = findViewById<TextView>(R.id.textView)

        // List of spinner items
        val list = listOf(
            "Ocean Blue",
            "Old lavender",
            "Orchid pink",
            "Rich black",
            "Royal yellow",
            "Rusty red"
        )

        // Initialize an array adapter for spinner
        val adapter = ArrayAdapter(
            context,
            android.R.layout.simple_spinner_dropdown_item,
            list
        )

        // Finally, data bind spinner with adapter
        spinner.adapter = adapter


        // Spinner on item selected listener
        spinner.onItemSelectedListener = object : AdapterView
        .OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                textView.text = "Selected: "
                // Get selected item text
                textView.append(
                    parent.getItemAtPosition(position).toString()
                )
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // Another interface callback
            }
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Spinner selected item background color

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this

        // Get the widgets reference from XML layout
        val spinner = findViewById<Spinner>(R.id.spinner)

        // list of spinner items
        val list = listOf(
            "Honeydew",
            "Laurel green",
            "Light salmon",
            "Bright maroon",
            "Cherry blossom pink",
            "Moss green",
            "Antique bronze"
        )

        // initialize an array adapter for spinner
        val adapter:ArrayAdapter<String> = object: ArrayAdapter<String>(
            context,
            android.R.layout.simple_spinner_dropdown_item,
            list
        ){
            override fun getDropDownView(
                position: Int,
                convertView: View?,
                parent: ViewGroup
            ): View {
                val view:TextView = super.getDropDownView(
                    position,
                    convertView,
                    parent
                ) as TextView
                // set item font family
                view.setTypeface(Typeface.SANS_SERIF,Typeface.BOLD)

                // set item padding
                view.setPaddingRelative(48,0,48,0)

                // set selected item style
                if (position == spinner.selectedItemPosition){
                    // selected item background color
                    view.background = ColorDrawable(
                        Color.parseColor("#FFF600")
                    )
                    // selected item text color
                    view.setTextColor(Color.parseColor("#2E2D88"))
                }

                return view
            }
        }

        // finally, data bind spinner with adapter
        spinner.adapter = adapter

        // set up initial selection
        spinner.setSelection(2)
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Spinner text size programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.Typeface
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.*


class MainActivity : Activity() {
    private lateinit var context:MainActivity

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

        // get the context
        context = this

        // get the widgets reference from XML layout
        val spinner = findViewById<Spinner>(R.id.spinner)


        // list of spinner items
        val list = listOf(
            "Alice blue",
            "Amaranth purple",
            "Antique brass",
            "Apple green",
            "Atomic tangerine",
            "Bitter lime",
            "Black chocolate"
        )


        // initialize an array adapter for spinner
        val adapter:ArrayAdapter<String> = object: ArrayAdapter<String>(
            context,
            android.R.layout.simple_spinner_dropdown_item,
            list
        ){
            override fun getDropDownView(
                position: Int,
                convertView: View?,
                parent: ViewGroup
            ): View {
                val view:TextView = super.getDropDownView(
                    position,
                    convertView,
                    parent
                ) as TextView

                // set the item padding
                view.setPaddingRelative(48,0,48,0)

                view.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL)

                // set item text size
                view.setTextSize(TypedValue.COMPLEX_UNIT_SP,24F)

                return view
            }
        }


        // finally, data bind spinner with adapter
        spinner.adapter = adapter
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="64dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials

android kotlin - ConstraintLayout center in parent programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.constraintlayout.widget.ConstraintSet.*
import androidx.transition.TransitionManager


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 checkbox = findViewById<CheckBox>(R.id.checkbox)
        val button = findViewById<Button>(R.id.button)

        button.setOnClickListener {
            val constraintSet = ConstraintSet()
            constraintSet.clone(rootLayout)

            // this block will put it horizontally center of parent
            // set check box constraint start to start of parent
            constraintSet.connect(
                checkbox.id, // the ID of the widget to be constrained
                START, // the side of the widget to constrain
                PARENT_ID, // the id of the widget to constrain to
                START // the side of widget to constrain to
            )

            // set check box constraint end to end of parent
            constraintSet.connect(
                checkbox.id, END, PARENT_ID, END
            )


            // this block put it vertically center
            // set check box constraint top to top of parent
            constraintSet.connect(checkbox.id,TOP, PARENT_ID, TOP)

            // set check box constraint bottom to bottom of parent
            constraintSet.connect(checkbox.id, BOTTOM, PARENT_ID, BOTTOM)


            // optionally, apply the constraints smoothly
            TransitionManager.beginDelayedTransition(rootLayout)

            // both blocks will put the check box exact center of parent
            // finally, apply the constraint set to constraint layout
            constraintSet.applyTo(rootLayout)
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:text="Put CheckBox Center In Parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Me" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - ConstraintLayout set margin programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout


class MainActivity : AppCompatActivity() {
    private lateinit var context: Context

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

        // Get the context
        context = this;

        // Get the widgets from XML layout
        val button = findViewById<Button>(R.id.button);
        val textView =  findViewById<TextView>(R.id.textView);

        // Text for text view
        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry. Lorem Ipsum has been the" +
                " industry's standard dummy text ever since the 1500s," +
                " when an unknown printer took a galley of type and" +
                " scrambled it to make a type specimen book."

        // Set the text view text
        textView.text = string

        // Set a button click listener
        button.setOnClickListener {
            // Get the text view layout parameters
            val layoutParams = textView.layoutParams
                    as ConstraintLayout.LayoutParams

            // Use this way if any side margin is already
            // defined in xml layout
            layoutParams.topMargin = 24.toDp(context)
            layoutParams.marginStart = 16.toDp(context)
            layoutParams.marginEnd = 34.toDp(context)
            layoutParams.bottomMargin = 8.toDp(context)

            // Another way to set margin for all sides
            /*layoutParams.setMargins(
                30.toDp(context), // left
                24.toDp(context), // top
                16.toDp(context), // right
                28.toDp(context) // bottom
            )*/

            // Finally, apply the layout params to text view
            textView.layoutParams = layoutParams
        }
    }
}


// Extension method to convert dp to equivalent pixels
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    this.toFloat(),
    context.resources.displayMetrics
).toInt()
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#FAEBD7"
        android:fontFamily="monospace"
        android:padding="12dp"
        android:textColor="#E52B50"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Set TextView  Margin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - ConstraintLayout remove constraint programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.constraintlayout.widget.ConstraintSet.*


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this

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

        button.setOnClickListener {
            val constraintSet = ConstraintSet()
            constraintSet.clone(rootLayout)

            // Remove text view top constraint
            constraintSet.clear(
                textView.id, // widget to remove constraint
                TOP // the Anchor to remove constraint from
            )

            // Finally, apply the constraint set to layout
            constraintSet.applyTo(rootLayout)
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Remove TextView Top Constraint"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:background="#FEFEFA"
        android:fontFamily="sans-serif"
        android:padding="12dp"
        android:text="Lorem ipsum dolor sit amet, consectetur
         adipiscing elit."
        android:textColor="#333399"
        android:textSize="24sp"
        android:textStyle="italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - ConstraintLayout set constraint programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.constraintlayout.widget.ConstraintSet.*


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this

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

        button.setOnClickListener {
            val constraintSet = ConstraintSet()
            constraintSet.clone(rootLayout)

            // put the text view bottom of button widget with margin
            constraintSet.connect(
                textView.id, // text view to change constraint
                TOP, // put text view top side bottom of button
                button.id, // button to put text view bellow it
                BOTTOM, // button bottom to put text view bellow it
                24.toDp(context) // margin (optional)
            )

            // horizontally center align the text view
            // text view constraint start to start of parent
            constraintSet.connect(
                textView.id,
                START,
                PARENT_ID,
                START
            )

            // text view constraint end to end of parent
            constraintSet.connect(
                textView.id,
                END,
                PARENT_ID,
                END
            )

            // finally, apply the constraint set to layout
            constraintSet.applyTo(rootLayout)
        }
    }
}

// Extension method to convert dp to equivalent pixels
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    this.toFloat(),
    context.resources.displayMetrics
).toInt()
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="16dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set TextView Constraint"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:background="#FEFEFA"
        android:padding="12dp"
        android:fontFamily="sans-serif"
        android:textStyle="italic"
        android:text="Lorem ipsum dolor sit amet, consectetur
         adipiscing elit. In dapibus urna id mauris maximus,
         at placerat nibh pretium. Donec ac mi orci.
         Suspendisse potenti. Nulla id ultrices enim.
         Phasellus leo velit, porttitor sit amet rhoncus
         eu, molestie non risus."
        android:textColor="#2E5894"
        android:textSize="24sp" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Underline TextView text programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.*
import android.os.Bundle
import android.text.SpannableString
import android.text.style.UnderlineSpan
import android.widget.*
import androidx.core.text.HtmlCompat


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


        // get the widgets reference from XML layout
        val buttonPaint = findViewById<Button>(R.id.buttonPaint)
        val buttonSpan = findViewById<Button>(R.id.buttonSpan)
        val buttonHtml = findViewById<Button>(R.id.buttonHtml)
        val buttonHtmlPart = findViewById<Button>(R.id.buttonHtmlPart)
        val textView = findViewById<TextView>(R.id.textView)


        // text to show on text view
        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry. Lorem Ipsum has been the" +
                " industry's standard dummy text ever since the 1500s," +
                " when an unknown printer took a galley of type" +
                " and scrambled it to make a type specimen book."

        textView.text = string


        // underline text view part of text by span
        buttonSpan.setOnClickListener {
            val text = SpannableString(string)
            text.setSpan(
                UnderlineSpan(),
                50, // start
                150, // end
                0 // flags
            )
            textView.text = text
        }


        // underline text view full text using html
        buttonHtml.setOnClickListener {
            val htmlString = "<u>$string</>"
            textView.text = HtmlCompat.fromHtml(
                htmlString,
                HtmlCompat.FROM_HTML_MODE_LEGACY
            )
        }


        // underline text view part of text using html
        buttonHtmlPart.setOnClickListener {
            val builder = StringBuilder(string)
                .insert(125, "<u>")
            builder.insert(175+3,"</u>")
            textView.text = HtmlCompat.fromHtml(
                builder.toString(),
                HtmlCompat.FROM_HTML_MODE_LEGACY
            )
        }


        // underline text view full text by paint
        buttonPaint.setOnClickListener {
            textView.paintFlags = textView.paintFlags or
                    Paint.UNDERLINE_TEXT_FLAG

            // you need to remove underline paint flag
            // to implement another way
            // to remove all paint flags
            //textView.paintFlags = 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/buttonSpan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UnderLine Text Part (Span)"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonHtml"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="UnderLine All Text (HTML)"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonSpan" />

    <Button
        android:id="@+id/buttonHtmlPart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="UnderLine Text Part (HTML)"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonHtml" />

    <Button
        android:id="@+id/buttonPaint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="UnderLine All Text (Paint)"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonHtmlPart" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textColor="#2A52BE"
        android:fontFamily="sans-serif"
        android:textSize="28sp"
        android:textStyle="italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonPaint"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - Add view to ConstraintLayout programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.widget.TextViewCompat


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this

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

        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry. Lorem Ipsum has been the" +
                " industry's standard dummy text ever since the 1500s," +
                " when an unknown printer took a galley of type" +
                " and scrambled it to make a type specimen book."


        button.setOnClickListener {
            val textView = TextView(context)
            textView.text = string

            // Set text view text appearance
            /*TextViewCompat.setTextAppearance(
                textView,
                android.R.style.TextAppearance_DeviceDefault_Large
            )*/

            // Add other configurations for the text view
            textView.apply {
                // text view font
                typeface = Typeface.MONOSPACE

                // text view background color
                background = ColorDrawable(
                    Color.parseColor("#F0EAD6"))

                // text view text color
                setTextColor(Color.parseColor("#87421F"))

                // text view text style
                setTypeface(textView.typeface,Typeface.ITALIC)
                //setTypeface(Typeface.SANS_SERIF,Typeface.ITALIC)

                // text view text size
                setTextSize(TypedValue.COMPLEX_UNIT_SP, 24F)

                // text view text padding
                setPadding(12.toDp(context),12.toDp(context),
                    12.toDp(context),12.toDp(context))
            }

            // text view width and height
            val params = LayoutParams(
                LayoutParams.MATCH_PARENT, // width
                LayoutParams.WRAP_CONTENT // height
            )

            // layout params for text view
            textView.layoutParams = params

            // generate a view id for text view
            textView.id = View.generateViewId()

            // finally, add the text view to constraint layout
            rootLayout.addView(textView)


            // Initialize a new constraint set
            val constraintSet = ConstraintSet()
            constraintSet.clone(rootLayout)

            // put the text view bottom of button with margin
            constraintSet.connect(
                textView.id,
                ConstraintSet.TOP,
                R.id.button,
                ConstraintSet.BOTTOM,
                24.toDp(context)
            )

            // start constraint with margin
            constraintSet.connect(
                textView.id,
                ConstraintSet.START,
                R.id.rootLayout,
                ConstraintSet.START,
                16.toDp(context)
            )

            // end constraint with margin
            constraintSet.connect(
                textView.id,
                ConstraintSet.END,
                R.id.rootLayout,
                ConstraintSet.END,
                16.toDp(context)
            )

            // finally, apply the constraint set to constraint layout
            constraintSet.applyTo(rootLayout)
        }
    }
}


// Extension method to convert dp to equivalent pixels
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),
    context.resources.displayMetrics
).toInt()
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:text="Create textView And Add"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - How to get substring from string

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and typesetting industry."

        textView.text = string

        // Returns a substring of this string that starts at the
        // specified startIndex and continues to the end of the string.
        val result = string.substring(
            50 // start index
        )

        textView.append("\n\n\n")
        textView.append("Substring start from index 50...\n")
        textView.append(result)


        /*
            documentation source kotlinlang.org
                Returns the substring of this string starting at the
                startIndex and ending right before the endIndex.
                    startIndex - the start index (inclusive).
                    endIndex - the end index (exclusive).
        */
        val result2 = string.substring(
            25, // start index inclusive
            65 // end index exclusive
        )

        textView.append("\n\n\n")
        textView.append("Substring start index 25 end index 65...\n")
        textView.append(result2)


        // Returns a substring specified by the given range of indices.
        val result3 = string.substring(
            15..60 // range
        )

        textView.append("\n\n\n")
        textView.append("Substring index range (15..60)...\n")
        textView.append(result3)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - String replace range example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and typesetting industry. Lorem Ipsum" +
                " has been the industry's standard dummy text" +
                " ever since the 1500s."

        textView.text = string

        // The end index of the range is included
        // in the part to be replaced.
        val result = string.replaceRange(
            25..100, // range
            " replaced string " // replacement
        )

        textView.append("\n\n\n")
        textView.append("Replace range (25..100) with " +
                "( replaced string )...\n\n")
        textView.append(result)


        /*
            documentation source kotlinlang.org
                Replaces the part of the string at the given
                range with the replacement char sequence.

                startIndex - the index of the first character to be replaced.
                endIndex - the index of the first character after
                           the replacement to keep in the string.
        */
        val result2 = string.replaceRange(
            40, // start index
            125, // end index
            " new string " // replacement
        )

        textView.append("\n\n\n")
        textView.append("Replace (start index 40 end index" +
                " 125) with ( new string )...\n\n")
        textView.append(result2)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - String replace example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and typesetting industry. Lorem Ipsum" +
                " has been the industry's standard dummy text" +
                " ever since the 1500s."

        textView.text = string

        /*
            documentation source kotlinlang.org
                Returns a new string with all occurrences
                of oldChar replaced with newChar.
        */
        val result = string.replace(
            'L', // old char
            '*', // new char
            true // ignore case Boolean = false
        )

        textView.append("\n\n\n")
        textView.append("Replace char 'L' with '*'" +
                " (ignore case)....\n\n")
        textView.append(result)


        /*
            Returns a new string obtained by replacing all
            occurrences of the oldValue substring in
            this string with the specified newValue string.
        */
        val result2 = string.replace(
            "ipsum", // old value
            "new value", // new value
            true // ignore case Boolean = false
        )

        textView.append("\n\n\n")
        textView.append("Replace string 'ipsum' with 'new value'" +
                " (ignore case)....\n\n")
        textView.append(result2)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        android:textSize="19sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - String remove surrounding example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and typesetting industry. Lorem Ipsum"

        textView.text = string

        /*
            documentation source kotlinlang.org
                Removes the given delimiter string from both the start and
                the end of this string if and only if it starts with
                and ends with the delimiter. Otherwise
                returns this string unchanged.
        */
        val result = string.removeSurrounding(
            "Lorem Ipsum" // delimiter
        )

        textView.append("\n\n\n")
        textView.append("Remove surrounding (Lorem Ipsum)...\n\n")
        textView.append(result)


        /*
            Removes from a string both the given prefix and suffix
            if and only if it starts with the prefix and ends with
            the suffix. Otherwise returns this string unchanged.
        */
        val result2 = string.removeSurrounding(
            "Lorem Ipsum is ", // prefix
            " industry. Lorem Ipsum" // suffix
        )

        textView.append("\n\n\n")
        textView.append("Remove surrounding (prefix 'Lorem Ipsum is '" +
                " and suffix ' industry. Lorem Ipsum')...\n\n")
        textView.append(result2)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - String remove range example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and typesetting industry."

        textView.text = string

        // Removes the part of a string at the given range.
        // The end index of the range is included in the removed part.
        val result = string.removeRange(
            10..50 // range
        )


        textView.append("\n\n\n")
        textView.append("After removing range (10..50)....\n")
        textView.append(result)

        /*
            documentation source kotlinlang.org
                Removes the part of a string at a given range.
                startIndex - the index of the first character to be removed.
                endIndex - the index of the first character after
                           the removed part to keep in the string.
                endIndex is not included in the removed part.
        */

        val result2 = result.removeRange(
            5, // start index
            25 // end index
        )

        textView.append("\n\n\n")
        textView.append("Removing from result" +
                " (start index 5, end index 25)....\n")
        textView.append(result2)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - String remove prefix and suffix example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string1 = "This is a sample string to" +
                " test remove prefix function."

        textView.text = string1

        /*  documentation source kotlinlang.org
                If this string starts with the given prefix,
                returns a copy of this string with the prefix
                removed. Otherwise, returns this string.
        */
        val result = string1.removePrefix("This")
        textView.append("\n\n")
        textView.append("After removing prefix(This)...\n")
        textView.append(result)


        val string2 = "This is a sample string to" +
                " test remove suffix function."

        textView.append("\n\n\n")
        textView.append(string2)

        /*
            If this string ends with the given suffix,
            returns a copy of this string with the suffix
            removed. Otherwise, returns this string.
        */
        val result2 = string2.removeSuffix("function.")
        textView.append("\n\n")
        textView.append("After removing suffix(function.)...\n")
        textView.append(result2)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - How to match two strings region

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string1 = "This is a sample string to test the function."

        val string2 = "This is another SAMPLE string to test the " +
                "string region matches method."

        textView.text = string1
        textView.append("\n\n")
        textView.append(string2)

        /*
            documentation source kotlinlang.org
                Returns true if the specified range in this char sequence
                is equal to the specified range in another char sequence.
        */

        val result = string1.regionMatches(
            9, // thisOffset: Int
            string2, //other: CharSequence
            15, // otherOffset: Int,
            13, // length: Int,
            true // ignoreCase: Boolean = false
        )

        textView.append("\n\n\n")
        textView.append("String1 and string2 region" +
                " (sample string) matches? $result")

    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - Prepend indent to string every line

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and \ntypesetting industry. Lorem Ipsum" +
                " has been the industry's \nstandard dummy text" +
                " ever since the 1500s, when \nan unknown printer" +
                " took a galley of type and \nscrambled it to" +
                " make a type specimen book."

        textView.text = string

        textView.append("\n\n\nAfter prepend indent....\n\n")

        // Prepends indent to every line of the original string.
        // Doesn't preserve the original line endings.
        val result = string.prependIndent(
            "     " // indent
        )

        textView.append(result)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        android:textSize="19sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - How to partition a string

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "This is A SAMple striNg."

        textView.text = string

        /*
            documentation source: kotlinlang.org
                Splits the original char sequence into pair of char sequences,
                where first char sequence contains characters for which
                predicate yielded true, while second char sequence
                contains characters for which predicate yielded false.
        */
        val result:Pair<String,String> = string.partition {
            it.isUpperCase()
        }

        textView.append("\n\n")
        textView.append("Uppercase characters....\n")
        textView.append(result.first)

        textView.append("\n\n")
        textView.append("Exclude uppercase characters....\n")
        textView.append(result.second)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - String padStart and padEnd example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the" +
                " printing and typesetting industry."

        textView.text = string

        // string is returned as is, when its
        // length is greater than the specified
        val afterPadStart10 = string.padStart(10,'*')
        textView.append("\n\nAfter pad start 10....\n")
        textView.append(afterPadStart10)

        val afterPadStart100 = string.padStart(100,'*')
        textView.append("\n\nAfter pad start 100....\n")
        textView.append(afterPadStart100)

        /*
            source: kotlinlang.org
            Returns a char sequence with content of this char sequence
            padded at the end to the specified length with
            the specified character or space.
         */
        val afterPadEnd = string.padEnd(
            string.length+5, // length - the desired string length.
            '*' // padChar - the character to pad string with
        )
        textView.append("\n\nAfter pad end length + 5....\n")
        textView.append(afterPadEnd)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - How to split string into lines

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        val string = "Lorem Ipsum is simply dummy text \nof the" +
                " printing and typesetting industry. Lorem" +
                " Ipsum has been the industry's \nstandard dummy" +
                " text ever since \nthe 1500s, when an unknown" +
                " printer took a galley of type \nand scrambled" +
                " it to make a type specimen book."

        textView.text = string

        /*
            source: kotlinlang.org
            Splits this char sequence to a list of lines delimited by
            any of the following character sequences: CRLF, LF or CR.

            The lines returned do not include terminating line separators.
        */

        // Split string into lines
        val lines:List<String> = string.lines()

        textView.append("\n\n\nLines (${lines.size})....")
        lines.forEach {
            textView.append("\n\n" + it)
        }
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#2A52BE"
        android:textStyle="normal"
        android:textSize="20sp"
        android:fontFamily="sans-serif-condensed"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - String isBlank and isEmpty example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "     "

        textView.text = "This string ($string)" +
                " length is " + string.length

        // Returns true if this string is empty
        // or consists solely of whitespace characters.
        textView.append("\n\nString is blank? ")
        textView.append(string.isBlank().toString())


        // Returns true if this char sequence is
        // empty (contains no characters).
        textView.append("\n\nString is empty? ")
        textView.append(string.isEmpty().toString())
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - How to filter string

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry. Lorem Ipsum has been the" +
                " industry's standard dummy text ever since the 1500s," +
                " when an unknown printer took a galley of type" +
                " and scrambled it to make a type specimen book."

        textView.text = string

        // Returns a string containing only those characters
        // from the original string that match the given predicate.

        // Filter digits from string.
        // Return a string with only digits.
        val filteredText = string.filter { it.isDigit() }
        textView.append("\n\nFilter digits.\n")
        textView.append(filteredText)


        // Returns a string containing only those characters from
        // the original string that do not match the given predicate.

        // Filter not digits from string.
        // Return a string without digits
        val filterNotText = string.filterNot{ it.isDigit() }
        textView.append("\n\nFilter not digits.\n")
        textView.append(filterNotText)
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

android kotlin - How to compare two strings

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string1 = "This is a sample string."
        val string2 = "This is a SAMPLE string."

        textView.text = "String 1 : \n$string1"
        textView.append("\n\nString 2 : \n$string2")


        // Compares two strings lexicographically,
        // optionally ignoring case differences.
        if (string1.compareTo(string2,ignoreCase = true) == 0){
            textView.append("\n\nBoth strings are equal, ignoring case.")
        }else{
            textView.append("\n\nBoth strings are not equal, ignoring case.")
        }


        // return zero for equal string
        // return positive integer when argument's ASCII value is smaller
        // return negative integer when argument's ASCII value is greater
        if (string1.compareTo(string2) == 0){
            textView.append("\n\nBoth strings are equal, Case sensitive.")
        }else{
            textView.append("\n\nBoth strings are not equal, Case sensitive.")
        }
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - Get string last index

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry. Lorem Ipsum has been the" +
                " industry's standard dummy text ever since the" +
                " 1500s, when an unknown printer took a galley" +
                " of type and scrambled it to make a type specimen book."
        textView.text = string

        // Returns the index of the last character in the
        // char sequence or -1 if it is empty.
        val lastIndex =string.lastIndex

        textView.append("\n\nLast index of string: $lastIndex")
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>

android kotlin - String capitalize decapitalize example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*


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

        // get the widgets reference from XML layout
        val textView = findViewById<TextView>(R.id.textView)

        // make textview content scrollable
        textView.movementMethod = ScrollingMovementMethod()


        val string = "this is a sample string."
        textView.text = string

        textView.append("\n\nAfter capitalize it....")
        // Returns a copy of this string
        // having its first letter uppercase.
        textView.append("\n" + string.replaceFirstChar {
            if (it.isLowerCase()) it.titlecase(Locale.ROOT)
            else it.toString()
        })


        val string2 = "This is another sample string."
        textView.append("\n\n\n" + string2)

        textView.append("\n\nAfter decapitalize it....")
        // Returns a copy of this string
        // having its first letter lowercase.
        textView.append("\n" + string2.replaceFirstChar {
            it.lowercase(Locale.ROOT)
        })
    }
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F8F8F8"
    android:padding="24dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fontFamily="sans-serif"
        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>