android kotlin - ViewPager example







MainActivity.kt



package com.cfsuman.kotlintutorials

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager


class MainActivity : AppCompatActivity() {

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

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


// Initialize a list of string values
val alphabets = listOf("a","b","c","d","e","f")

// Initialize a new pager adapter instance with list
val adapter = AlphabetPagerAdapter(alphabets)

// Finally, data bind the view pager widget with pager adapter
viewPager.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:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>




page_layout.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">

<TextView
android:id="@+id/tvColor"
android:layout_width="0dp"
android:layout_height="0dp"
android:fontFamily="sans-serif"
android:gravity="center"
android:textSize="250sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvFooter"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/tvFooter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end|bottom"
android:textSize="20sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>




AlphabetPagerAdapter.kt



package com.cfsuman.kotlintutorials

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter


class AlphabetPagerAdapter(private val list: List<String>)
: PagerAdapter() {

override fun isViewFromObject(v: View, `object`: Any): Boolean {
// Return the current view
return v === `object` as View
}


override fun getCount(): Int {
// Count the items and return it
return list.size
}


override fun instantiateItem(
parent: ViewGroup, position: Int): Any {
// Get the view from pager page layout
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.page_layout,parent,false)

// Get the widgets reference from layout
val tvColor: TextView = view.findViewById(R.id.tvColor)
val tvFooter: TextView = view.findViewById(R.id.tvFooter)

// Set the text views text
tvColor.text = list[position]
tvFooter.text = "Page ${position+1} of ${list.size}"

// Add the view to the parent
parent.addView(view)

// Return the view
return view
}


override fun destroyItem(
parent: ViewGroup, position: Int, `object`: Any) {
// Remove the view from view group specified position
parent.removeView(`object` as View)
}
}







android kotlin - Handler and Runnable example






MainActivity.kt



package com.cfsuman.kotlinexamples

import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


class MainActivity : AppCompatActivity() {

private lateinit var mRandom:Random
private lateinit var mHandler: Handler
private lateinit var mRunnable:Runnable

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

// Initialize a new Random instance
mRandom = Random()

// Initialize the handler instance
mHandler = Handler()

// Set a click listener for run button
button_run.setOnClickListener{
mRunnable = Runnable {
// Do something here
root_layout.setBackgroundColor(randomHSVColor())
text_view.text = "Handler Example\n" +
"Random Number : ${mRandom.nextInt(100)}"

// Schedule the task to repeat after 1 second
mHandler.postDelayed(
mRunnable, // Runnable
1000 // Delay in milliseconds
)
}

// Schedule the task to repeat after 1 second
mHandler.postDelayed(
mRunnable, // Runnable
1000 // Delay in milliseconds
)
}



// Set a click listener for stop button
button_stop.setOnClickListener{
// Stop the periodic task
mHandler.removeCallbacks(mRunnable)

// Change the text view text
text_view.text = "Handler call backs removed."
}



// Set a click listener for handler short code form button
button_short.setOnClickListener{
mHandler.postDelayed({
// Change text view text
text_view.text = "Handler Short Code\n" +
"Random Number : ${mRandom.nextInt(100)}"

// Change the text view text color
text_view.setTextColor(randomHSVColor())

// Change layout background color
root_layout.setBackgroundColor(Color.WHITE)
}, 3000) // 3 seconds delay task execution

}
}



// Custom method to generate random HSV color
fun randomHSVColor(): Int {
// Generate a random hue value between 0 to 360
val hue = mRandom.nextInt(361)
// We make the color depth full
val saturation = 1.0f
// We make a full bright color
val value = 1.0f
// We avoid color transparency
val alpha = 255
// Finally, generate the color
// Return the color
return Color.HSVToColor(alpha, floatArrayOf(hue.toFloat(), saturation, value))
}
}




activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#edf9ee"
android:orientation="vertical"
android:padding="16dp"
>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Run A Task"
android:textSize="30sp"
android:layout_margin="20dp"
/>
<Button
android:id="@+id/button_run"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run Handler"
/>
<Button
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove Callbacks"
/>
<Button
android:id="@+id/button_short"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Handler Short Code"
/>
</LinearLayout>

















android kotlin - SwipeRefreshLayout example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

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

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


// Set an on refresh listener for swipe refresh layout
swipeRefreshLayout.setOnRefreshListener {
textView.text = "Refreshed & Generated Random Number\n" +
"${Random.nextInt(500)}"

// Hide swipe to refresh icon animation
swipeRefreshLayout.isRefreshing = false
}
}
}




activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F8F8F8"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Swipe to refresh me"
android:gravity="center"
android:textSize="28sp"
android:fontFamily="sans-serif"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>





build.gradle [app] [dependencies]



implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'







android kotlin - Snackbar example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.google.android.material.snackbar.Snackbar


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 buttonSimple = findViewById<Button>(R.id.buttonSimple)
val buttonAction = findViewById<Button>(R.id.buttonAction)
val buttonStyle = findViewById<Button>(R.id.buttonStyle)


// Button click listener
buttonSimple.setOnClickListener{
Snackbar.make(
rootLayout, // Parent view
"Hello Snackbar!", // Message to show
Snackbar.LENGTH_SHORT // How long to display the message.
).show()
}


// Button to show a snack bar with action enabled
buttonAction.setOnClickListener{
// Change the app background color
rootLayout.setBackgroundColor(
Color.parseColor("#A8C3BC")
)

// Show a snack bar for undo option
Snackbar.make(
rootLayout, // Parent view
"We changes app background color.", // Message to show
Snackbar.LENGTH_LONG //
).setAction( // Set an action for snack bar
"Undo" // Action button text
){ // Action button click listener
// Do something when undo action button clicked
rootLayout.setBackgroundColor(
Color.parseColor("#F8F8F8")
)
}.show() // Finally show the snack bar
}


// Customize the snack bar style
buttonStyle.setOnClickListener{
// Initialize a new snack bar instance
val snackbar = Snackbar.make(
rootLayout,
"This is a styled snack bar.",
Snackbar.LENGTH_INDEFINITE
)

// Get the snack bar root view
val snackRootView = snackbar.view

// Get the snack bar text view
val snackTextView = snackRootView
.findViewById<TextView>(
com.google.android.material.R.id.snackbar_text)

// Get the snack bar action view
val snackActionView = snackRootView
.findViewById<Button>(
com.google.android.material.R.id.snackbar_action)

// Change the snack bar root view background color
snackRootView.setBackgroundColor(
Color.parseColor("#A4DDED"))

// Change the snack bar text view text color
snackTextView.setTextColor(
Color.parseColor("#2D383A"))

// Change snack bar text view text style
snackTextView.setTypeface(
Typeface.MONOSPACE,Typeface.BOLD_ITALIC)

// Change the snack bar action button text color
snackActionView.setTextColor(
Color.parseColor("#002147"))

// Set an action for snack bar
snackbar.setAction("Hide Me") {
// Hide the snack bar
snackbar.dismiss()
}

// Finally, display the snack bar
snackbar.show()
}
}
}




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:padding="24dp"
android:background="#F8F8F8">

<Button
android:id="@+id/buttonSimple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple Snackbar"
android:textAllCaps="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Snackbar Action"
android:textAllCaps="false"
app:layout_constraintStart_toStartOf="@+id/buttonSimple"
app:layout_constraintTop_toBottomOf="@+id/buttonSimple" />

<Button
android:id="@+id/buttonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Snackbar Style"
android:textAllCaps="false"
app:layout_constraintStart_toStartOf="@+id/buttonAction"
app:layout_constraintTop_toBottomOf="@+id/buttonAction" />

</androidx.constraintlayout.widget.ConstraintLayout>






android kotlin - Toolbar example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar


class MainActivity : AppCompatActivity() {
private lateinit var textView: TextView

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

// Get the widgets from XML layout
val toolbar = findViewById<Toolbar>(R.id.toolbar);
textView = findViewById(R.id.textView);

// Configure the Toolbar
toolbar.apply {
title = "Toolbar title"
setTitleTextColor(Color.WHITE)
setLogo(R.drawable.ic_action_help)
//subtitle = "Toolbar Subtitle"
//setSubtitleTextColor(Color.WHITE)
}

// Set the toolbar as support action bar
setSupportActionBar(toolbar)
}


override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu to use in the action bar
val inflater = menuInflater
inflater.inflate(R.menu.toolbar_menu, menu)
return super.onCreateOptionsMenu(menu)
}


override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar menu items
when (item.itemId) {
R.id.action_cut -> {
textView.text = "Cut Clicked."
return true
}
R.id.action_copy -> {
textView.text = "Copy Clicked."
return true
}
R.id.action_paste -> {
textView.text = "Paste Clicked."
return true
}
R.id.action_new -> {
textView.text = "New Clicked."
return true
}
}
return super.onOptionsItemSelected(item)
}
}




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="#F8F8F8">

<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:elevation="4dp"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="sans-serif"
android:textSize="24sp"
android:gravity="center" />

</androidx.constraintlayout.widget.ConstraintLayout>




Parent Theme



Theme.MaterialComponents.Light.NoActionBar




res/menu/toolbar_menu.xml



<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_cut"
android:title="Cut"
app:showAsAction="always"
android:icon="@drawable/ic_action_cut" />
<item
android:id="@+id/action_copy"
android:title="Copy"
app:showAsAction="always|withText"
android:icon="@drawable/ic_action_copy" />
<item
android:id="@+id/action_paste"
android:title="Paste"
app:showAsAction="ifRoom"
android:icon="@drawable/ic_action_paste" />
<item
android:id="@+id/action_new"
android:title="New"
app:showAsAction="never"
android:icon="@drawable/ic_action_new" />
</menu>







android kotlin - Menu and onCreateOptionsMenu example


Kotlin Menu & onCreateOptionsMenu



The Menu is a component of the native android SDK. The Menu is an android user interface component. Android SDK’s Menu API use to present user actions and other options in an Activity. The options menu is the primary menu for an activity where developers place the actions.




The following android kotlin tutorial will demonstrate how we can create an options Menu and place it in the android app user interface. This tutorial is written in Kotlin programming language with native android SDK tools.




Android SDK provides a standard XML format to define menu items. Instead, kotlin code developers should define the menu and its items in an XML menu resource. Then android developers can inflate the menu resource in the activity or fragment it as a Menu object.




Menu resource is easy to visualize and also easy to organize the menu structure in XML. The Menu resource separates content from Kotlin code. It allows us to create alternative menu configurations for different android platform versions, screen sizes, and other configurations.




The Menu resource XML content is built with several elements such as the menu, item, and group. The group is an invisible container for item elements. The group allows categorizing of menu items and shares properties such as active state and visibility. Menu ‘item’ element consists of several objects such as an id, title, icon, and showAsAction.




The onCreateOptionsMenu() method allows us to initialize the contents of the Activity’s standard options menu. In this method, developers inflate the XML Menu resource and display it in the toolbar. The onOptionsItemSelected() method allows developers to define the menu item’s click listener.




This android kotlin tutorial code is written in an android studio IDE. Copy the code into your android studio IDE and run it on an emulator to test how we implement an options menu in our tutorial. At the bottom of this kotlin tutorial, we display 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.Menu
import android.view.MenuItem
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
private lateinit var textView:TextView

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

// Get the widgets reference from XML layout
textView = findViewById(R.id.textView)

// Get the support action bar
val actionBar = supportActionBar

// Set the action bar title
actionBar?.title = "Kotlin Menu"
}


override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu to use in the action bar
val inflater = menuInflater
inflater.inflate(R.menu.toolbar_menu, menu)
return super.onCreateOptionsMenu(menu)
}


override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar menu items
when (item.itemId) {
R.id.action_cut -> {
textView.text = "Cut"
return true
}
R.id.action_copy -> {
textView.text = "Copy"
return true
}
R.id.action_paste -> {
textView.text = "Paste"
return true
}
R.id.action_new -> {
textView.text = "New"
return true
}
}
return super.onOptionsItemSelected(item)
}
}




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:padding="24dp"
android:background="#DCDCDD">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tap an item from action bar menu."
android:textColor="#191970"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>




res/menu/toolbar_menu.xml



<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_cut"
android:title="Cut"
app:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_cut"/>
<item
android:id="@+id/action_copy"
android:title="Copy"
app:showAsAction="always|withText"/>
<item
android:id="@+id/action_paste"
android:title="Paste"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/action_new"
android:title="New"
app:showAsAction="ifRoom"/>
</menu>







android kotlin - Convert dp to px to dp







MainActivity.kt



package com.example.jetpack

import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.roundToInt
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

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

// generate random integer and float value
val random = Random.nextInt(50,100)
val randomFloat = Random.nextFloat() * 100

// show the screen density
textView.text = "Screen Density: ${displayMetrics.density}"


// convert integer dp value to equivalent pixels value
textView.append("\n\nRandom Number : $random")
val pixels = random.dpToPixels(this)
textView.append("\n$random dp = $pixels pixels (Float)")
textView.append("\n$random dp = ${pixels.roundToInt()} pixels (Int)")


// convert integer pixels value to equivalent dp value
val dp = random.pixelsToDp(this)
textView.append("\n\n$random pixels = $dp dp (Float)")
textView.append("\n$random pixels = ${dp.roundToInt()} dp (Int)")


// convert float pixels and dp to equivalent dp and pixels value
textView.append("\n\nRandom Float : $randomFloat")
textView.append("\n$randomFloat dp =" +
" ${randomFloat.dpToPixels(this)} pixels")
textView.append("\n$randomFloat pixels =" +
" ${randomFloat.pixelsToDp(this)} dp")
}
}


// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(context: Context):Float = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),context.resources.displayMetrics
)

// input float dp value to convert equivalent pixels
fun Float.dpToPixels(context: Context):Float = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,this,context.resources.displayMetrics
)


// extension function to convert pixels to equivalent dp
fun Int.pixelsToDp(context: Context):Float{
return this / (context.resources
.displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
}

// input float pixels value to convert equivalent dp
fun Float.pixelsToDp(context: Context):Float{
return this / (context.resources
.displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
}


// extension property to get display metrics instance
val Activity.displayMetrics: DisplayMetrics
get() {
val displayMetrics = DisplayMetrics()

if (Build.VERSION.SDK_INT >= 30){
display?.apply {
getRealMetrics(displayMetrics)
}
}else{
// getMetrics() method was deprecated in api level 30
windowManager.defaultDisplay.getMetrics(displayMetrics)
}

return displayMetrics
}





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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E5E4E2"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:fontFamily="sans-serif-condensed"
android:textColor="#191970"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>


android kotlin - TimePickerDialog example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.*
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 button = findViewById<Button>(R.id.button)

// Set a click listener for button widget
button.setOnClickListener{
// Initialize a new TimePickerFragment
val newFragment = TimePickerFragment()
// Show the time picker dialog
newFragment.show(
supportFragmentManager,
"Time Picker"
)
}
}
}




TimePickerFragment.kt



package com.cfsuman.kotlintutorials

import android.app.TimePickerDialog
import android.os.Bundle
import android.widget.TextView
import android.app.Dialog
import java.util.Calendar
import android.widget.TimePicker
import androidx.fragment.app.DialogFragment


class TimePickerFragment : DialogFragment(),
TimePickerDialog.OnTimeSetListener {
private lateinit var calendar:Calendar

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Initialize a Calendar instance
calendar = Calendar.getInstance()

// Get the system current hour and minute
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)

// Create a TimePickerDialog with system current time
// Return the TimePickerDialog
return TimePickerDialog(
requireActivity(), // Context
// Put 0 to system default theme or remove this parameter
0, // Theme
this, // TimePickerDialog.OnTimeSetListener
hour, // Hour of day
minute, // Minute
false // Is 24 hour view
)
}


override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
// Do something with the returned time
val textView:TextView = requireActivity()
.findViewById(R.id.textView) as TextView

textView.text = "Selected Time ${getHourAMPM(hourOfDay)}" +
":$minute ${getAMPM(hourOfDay)}"
}



// Custom method to get AM PM value from provided hour
private fun getAMPM(hour:Int):String{
return if(hour>11)"PM" else "AM"
}


// Custom method to get hour for AM PM time format
private fun getHourAMPM(hour:Int):Int{
// Return the hour value for AM PM time format
var modifiedHour = if (hour>11)hour-12 else hour
if (modifiedHour == 0){modifiedHour = 12}
return modifiedHour
}
}




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="Show TimePicker Dialog"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:fontFamily="sans-serif"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>






android kotlin - DatePickerDialog example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.content.Context
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity


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

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

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


// Set a click listener for button widget
button.setOnClickListener{
// Initialize a new DatePickerFragment
val datePickerFragment = DatePickerFragment()

// Show the date picker dialog
datePickerFragment.show(
supportFragmentManager,
"Date Picker"
)
}
}
}




DatePickerFragment.kt



package com.cfsuman.kotlintutorials

import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import android.widget.TextView
import android.widget.DatePicker
import androidx.fragment.app.DialogFragment
import java.text.DateFormat
import java.util.Calendar


class DatePickerFragment : DialogFragment(),
DatePickerDialog.OnDateSetListener {

private lateinit var calendar:Calendar

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Initialize a calendar instance
calendar = Calendar.getInstance()

// Get the system current date
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)

// Initialize a new date picker dialog and return it
return DatePickerDialog(
requireActivity(), // Context
// Put 0 to system default theme or remove this parameter
this, // DatePickerDialog.OnDateSetListener
year, // Year
month, // Month of year
day // Day of month
)
}


// When date set and press ok button in date picker dialog
override fun onDateSet(
view: DatePicker, year: Int, month: Int, day: Int) {
// Display the selected date in text view
requireActivity().findViewById<TextView>(R.id.textView)
.text = "Selected date : " + formatDate(year,month,day)
}


// Custom method to format date
private fun formatDate(year:Int, month:Int, day:Int):String{
// Create a Date variable/object with user chosen date
calendar.set(year, month, day, 0, 0, 0)
val chosenDate = calendar.time

// Format the date picker selected date
val df = DateFormat.getDateInstance(DateFormat.MEDIUM)
return df.format(chosenDate)
}
}




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:padding="24dp"
android:background="#F8F8F8">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:padding="16dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show DatePicker Dialog"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>






android kotlin - DatePicker example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import java.text.DateFormat
import java.util.*
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
private lateinit var calendar:Calendar

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)
val datePicker = findViewById<DatePicker>(R.id.datePicker)
val buttonGet = findViewById<Button>(R.id.buttonGet)
val buttonSet = findViewById<Button>(R.id.buttonSet)


// Initialize a new calendar instance
calendar = Calendar.getInstance()

// Get the Calendar current year, month and day of month
val thisYear = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)


// Initialize the date picker widget with system current date
datePicker.init(
thisYear,
month,
day
) { view, year, monthOfYear, dayOfMonth ->
// Do something when the date changed in date picker object
// Display the date picker selected date on text view
textView.text = "Date changed : " +
"${formatDate(year, monthOfYear, dayOfMonth)}"
}


// Set date programmatically
buttonSet.setOnClickListener{
// Update the date picker date by a random date
// Kotlin Random range(inclusive,exclusive)
val year = Random.nextInt(1999,2026)
val month = Random.nextInt(0,12)
val day = Random.nextInt(0,28)

// Update the date picker with random date
datePicker.updateDate(
year, // Year
month, // The month which is starting from zero.
day // Day of month
)
}


// Get date programmatically
buttonGet.setOnClickListener{
// Get the date picker widget selected date
val selectedDate = formatDate(datePicker.year,
datePicker.month,datePicker.dayOfMonth)
// Display the date picker selected formatted date
textView.text = "Selected date : $selectedDate"
}
}


// Custom method to format date
private fun formatDate(year:Int, month:Int, day:Int):String{
// Create a Date variable/object with user chosen date
calendar.set(year, month, day, 0, 0, 0)
val chosenDate = calendar.time

// Format the date picker selected date
val df = DateFormat.getDateInstance(DateFormat.MEDIUM)
return df.format(chosenDate)
}
}




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">

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#E6E5E5"
android:fontFamily="sans-serif"
android:textSize="20sp"
android:textAlignment="center"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:calendarViewShown="false"
android:datePickerMode="spinner"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<Button
android:id="@+id/buttonGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Get Date"
app:layout_constraintStart_toStartOf="@+id/datePicker"
app:layout_constraintTop_toBottomOf="@+id/datePicker" />

<Button
android:id="@+id/buttonSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Set Date"
app:layout_constraintBottom_toBottomOf="@+id/buttonGet"
app:layout_constraintStart_toEndOf="@+id/buttonGet" />

</androidx.constraintlayout.widget.ConstraintLayout>




android kotlin - TimePicker example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random


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)
val timePicker = findViewById<TimePicker>(R.id.timePicker)
val buttonGet = findViewById<Button>(R.id.buttonGet)
val buttonSet = findViewById<Button>(R.id.buttonSet)
val buttonToggle = findViewById<Button>(R.id.buttonToggle)


// Set a time change listener for time picker widget
timePicker.setOnTimeChangedListener{
view,hourOfDay,minute->
textView.text = "Time Changed ${getHourAMPM(hourOfDay)} " +
": $minute ${getAMPM(hourOfDay)}"
}


// Set a random time
buttonSet.setOnClickListener{
// Set a random time
setPickerTime(timePicker)
}


// Set a click listener for get time button widget
buttonGet.setOnClickListener{
// Display the picker current time on text view
textView.text = "Selected Time : ${getPickerTime(timePicker)}"
}


// Toggle time picker 24 hour view
buttonToggle.setOnClickListener{
if(timePicker.is24HourView){
timePicker.setIs24HourView(false)
}else{
timePicker.setIs24HourView(true)
}
}
}


// Get time picker current time as string
private fun getPickerTime(timePicker: TimePicker):String{
val hour = timePicker.hour
val minute = timePicker.minute
return "${getHourAMPM(hour)} : $minute ${getAMPM(hour)}"
}


// Get AM PM value from provided hour
private fun getAMPM(hour:Int):String{
return if(hour>11)"PM" else "AM"
}


// Get hour for AM PM time format
private fun getHourAMPM(hour:Int):Int{
// Return the hour value for AM PM time format
var modifiedHour = if (hour>11)hour-12 else hour
if (modifiedHour == 0){modifiedHour = 12}
return modifiedHour
}


// Set time picker random time
private fun setPickerTime(timePicker: TimePicker){
// Get random time
// Kotlin random range(inclusive,exclusive)
val hour = Random.nextInt(0,24)
val minute = Random.nextInt(0,60)

timePicker.hour = hour
timePicker.minute = minute
}
}




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">

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#E6E5E5"
android:fontFamily="sans-serif"
android:textSize="20sp"
android:textAlignment="center"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:timePickerMode="spinner"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<Button
android:id="@+id/buttonGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Get Time"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/timePicker" />

<Button
android:id="@+id/buttonSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Set Time"
app:layout_constraintBottom_toBottomOf="@+id/buttonGet"
app:layout_constraintStart_toEndOf="@+id/buttonGet" />

<Button
android:id="@+id/buttonToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:text="Toggle 24"
app:layout_constraintBottom_toBottomOf="@+id/buttonSet"
app:layout_constraintStart_toEndOf="@+id/buttonSet" />

</androidx.constraintlayout.widget.ConstraintLayout>






android kotlin - Create CardView programmatically






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams


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)


// Set a click listener for button widget
button.setOnClickListener{
// Disable the button itself
it.isEnabled = false

// Initialize a new CardView instance
val cardView = CardView(context)

// Initialize a new ConstraintLayout LayoutParams instance
// CardView width and height
val layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT, // CardView width
LayoutParams.WRAP_CONTENT // CardView height
)

// Set top margin for card view
layoutParams.topMargin = 64

// Put the CardView bottom of the button
layoutParams.topToBottom = button.id

// Set the card view layout params
cardView.layoutParams = layoutParams


// Set the CardView other configurations
cardView.apply {
// Set the card view corner radius
radius = 12F

// Set the card view content padding
setContentPadding(32,32,32,32)

// Set the card view background color
setCardBackgroundColor(Color.LTGRAY)

// Set card view elevation
cardElevation = 8F

// Set card view maximum elevation
maxCardElevation = 12F

// Set a click listener for card view
setOnClickListener{
Toast.makeText(
applicationContext,
"Card clicked.",
Toast.LENGTH_SHORT).show()
}

// Add an ImageView to the CardView
cardView.addView(generateImageView())
}


// Finally, add the CardView in root layout
rootLayout.addView(cardView)
}
}


// Custom method to generate an image view
private fun generateImageView(): ImageView{
val imageView = ImageView(context)
val params = LayoutParams(
LayoutParams.WRAP_CONTENT,
650
)
imageView.layoutParams = params
imageView.setImageResource(R.drawable.flower2)
imageView.scaleType = ImageView.ScaleType.CENTER_CROP
return imageView
}
}




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="Create CardView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>





android kotlin - EditText example






MainActivity.kt



package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.*
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 tvOutput = findViewById<TextView>(R.id.tvOutput)
val editText = findViewById<EditText>(R.id.editText)
val buttonSet = findViewById<Button>(R.id.buttonSet)
val buttonGet = findViewById<Button>(R.id.buttonGet)
val buttonClear = findViewById<Button>(R.id.buttonClear)

// Set some text to the EditText
buttonSet.setOnClickListener{
editText.setText("Jones")
}


// Get the EditText text on button click event
buttonGet.setOnClickListener{
// Ensure that the EditText is not empty
val inputtedText = editText.text
if(inputtedText.isNotEmpty()){ // EditText validation
// Display the EditText text in toast message
tvOutput.text = "Get Text : $inputtedText"
}else{
tvOutput.text = "EditText is empty"
}
}


// Empty the edit text
buttonClear.setOnClickListener{
editText.text.clear()
//editText.setText("")
}


// Set a text change listener for edit text object
editText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(p0: Editable?) {
// Do something after text changed
}

override fun beforeTextChanged(
p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
// Do something before text changed on EditText
}

override fun onTextChanged(
p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
// Do something on text changed in EditText
// Display the EditText change text on TextView real time
if (editText.text.trim().isEmpty()){
tvOutput.text = "EditText is empty"
}else{
tvOutput.text = editText.text
}
}
})
}
}




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">

<TextView
android:id="@+id/tvOutput"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textStyle="italic"
android:padding="12dp"
android:textSize="22sp"
android:background="#EAEAEA"
android:textAlignment="center"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:hint="Input your name here"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvOutput" />

<Button
android:id="@+id/buttonSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Set Text"
app:layout_constraintStart_toStartOf="@+id/editText"
app:layout_constraintTop_toBottomOf="@+id/editText" />

<Button
android:id="@+id/buttonGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="Get Text"
app:layout_constraintBottom_toBottomOf="@+id/buttonSet"
app:layout_constraintStart_toEndOf="@+id/buttonSet" />

<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="Clear"
app:layout_constraintBottom_toBottomOf="@+id/buttonGet"
app:layout_constraintStart_toEndOf="@+id/buttonGet" />

</androidx.constraintlayout.widget.ConstraintLayout>







android kotlin - AutoCompleteTextView example


AutoCompleteTextView



The AutoCompleteTextView is an editable text view. The AutoCompleteTextView shows completion suggestions automatically while the app user is typing. The AutoCompleteTextView’s list of suggestions is displayed in a drop-down menu. The android app users can choose an item from the suggestions to replace the content of the edit box with.




The android app users can dismiss the AutoCompleteTextView suggestions drop-down menu any time by pressing the back key, or if no item is selected in the drop-down, by pressing the enter key.




So, from where did the AutoCompleteTextView suggestions are coming from? The AutoCompleteTextView suggestions list is obtained from a data adapter. The AutoCompleteTextView suggestions appear only after a given number of characters defined by the ‘threshold’.




So, how we implemented the AutoCompleteTextView in our tutorial? At first, we create an array of String values. Then we create an instance of ArrayAdapter with this array. Next, we bind this ArrayAdapter instance with the AutoCompleteTextView. So our AutoCompleteTextView shows the suggestions from the array values. After it, we define a threshold value for the AutoCompletetextView.




The important event is the AutoCompleteTextView item click listener. Using the onItemClickListener we hide the soft keyboard programmatically. We also get the user-selected suggestion programmatically in real time. We also can show the selected item in a toast message. Finally, we set a dismiss listener for the AutoCompleteTextView widget. When the suggestions drop-down menu is dismissed we display a toast message.




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 an AutoCompleteTextView widget in an android application.




And how we show the suggestions for the AutoCompleteTextView and handle the user selection in this android 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.content.Context
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout


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

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)
autoCompleteTextView = findViewById(R.id.autoCompleteTextView)

// Initialize a new array with elements
val colors = arrayOf(
"Azure", "Aqua", "Amber", "Red",
"Green", "Blue", "Maroon", "Magenta",
"Gold", "GreenYellow","Ghost white"
)

// Initialize a new array adapter object
val adapter = ArrayAdapter<String>(
this, // Context
android.R.layout.simple_dropdown_item_1line, // Layout
colors // Array
)

// Set the AutoCompleteTextView adapter
autoCompleteTextView.setAdapter(adapter)

// Auto complete threshold
// The minimum number of characters to type to show the drop down
autoCompleteTextView.threshold = 1

// Set an item click listener for auto complete text view
autoCompleteTextView.onItemClickListener = AdapterView
.OnItemClickListener{
parent,view,position,id->
val selectedItem = parent.getItemAtPosition(position)
.toString()
// Display the clicked item using toast
showToast("Selected : $selectedItem")
// Hide soft keyboard
hideSoftKeyboard()
}

// Set a dismiss listener for auto complete text view
autoCompleteTextView.setOnDismissListener {
showToast("Suggestion closed.")
}

// Hide soft keyboard on root layout click
rootLayout.setOnClickListener {
hideSoftKeyboard()
autoCompleteTextView.clearFocus()
}
}

// Function to show toast message
private fun showToast(message:String){
Toast.makeText(context,message,Toast.LENGTH_SHORT).show()
}

// Function to hide soft keyboard programmatically
private fun hideSoftKeyboard(){
(getSystemService(
INPUT_METHOD_SERVICE) as InputMethodManager
).apply {
hideSoftInputFromWindow(currentFocus?.windowToken, 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:padding="24dp"
android:background="#F8F8F8">

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="textNoSuggestions"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>







android kotlin - Fragment example






MainActivity.kt



package com.cfsuman.kotlinexamples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

// Set a click listener for first button widget
button1.setOnClickListener {
// Get the text fragment instance
val textFragment = TextFragment()

// Get the support fragment manager instance
val manager = supportFragmentManager

// Begin the fragment transition using support fragment manager
val transaction = manager.beginTransaction()

// Replace the fragment on container
transaction.replace(R.id.fragment_container,textFragment)
transaction.addToBackStack(null)

// Finishing the transition
transaction.commit()
}


// Set a click listener for second button widget
button2.setOnClickListener {
// Get the text fragment instance
val imageFragment = ImageFragment()

// Get the support fragment manager instance
val manager = supportFragmentManager

// Begin the fragment transition using support fragment manager
val transaction = manager.beginTransaction()

// Replace the fragment on container
transaction.replace(R.id.fragment_container,imageFragment)
transaction.addToBackStack(null)

// Finishing the transition
transaction.commit()
}
}
}




activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:background="#f8fdf8"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Text Fragment"
android:textAllCaps="false"
/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Image Fragment"
android:textAllCaps="false"
/>
<LinearLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="#c1cfba"
/>
</LinearLayout>





TextFragment.kt



package com.cfsuman.kotlinexamples


import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast


class TextFragment : Fragment(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Get the custom view for this fragment layout
val view = inflater!!.inflate(R.layout.layout_text_fragment,container,false)

// Get the text view widget reference from custom layout
val tv = view.findViewById<TextView>(R.id.text_view)

// Set a click listener for text view object
tv.setOnClickListener{
// Change the text color
tv.setTextColor(Color.RED)

// Show click confirmation
Toast.makeText(view.context,"TextView clicked.",Toast.LENGTH_SHORT).show()
}

// Return the fragment view/layout
return view
}

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

override fun onAttach(context: Context?) {
super.onAttach(context)
}

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

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

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

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




layout_text_fragment.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a sample text from Text Fragment"
android:textSize="50sp"
/>
</LinearLayout>





ImageFragment.kt



package com.cfsuman.kotlinexamples


import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


class ImageFragment : Fragment(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Return the fragment view/layout
return inflater!!.inflate(R.layout.layout_image_fragment,container,false)
}

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

override fun onAttach(context: Context?) {
super.onAttach(context)
}

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

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

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

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




layout_image_fragment.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
>
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/flower"
/>
</LinearLayout>