MainActivity.kt
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.widget.*
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val context:MainActivity = this
// get the widgets reference from XML layout
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val builder = MaterialAlertDialogBuilder(context)
// dialog title
builder.setTitle("Dialog Title")
// set alert dialog message text color
val message = SpannableString(
"Lorem ipsum dolor sit amet, consectetur" +
" adipiscing elit. Suspendisse rutrum metus" +
" nisi, placerat sollicitudin nibh cursus eget." +
" Donec vitae turpis ut metus dapibus sagittis" +
" ut a ante. Morbi lectus arcu, porttitor sit" +
" amet ipsum et, ultricies condimentum massa." +
" Vestibulum sed mi ultricies, dictum metus" +
" sit amet, fringilla est.")
message.setSpan(
ForegroundColorSpan(Color.BLUE),
0,
message.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
// dialog message
builder.setMessage(message)
// alert dialog buttons
builder.setPositiveButton("OK",null)
builder.setNegativeButton("No",null)
builder.setNeutralButton("Cancel",null)
// finally, create the alert dialog and show it
val dialog = builder.create()
dialog.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle dependencies[add]
// Material components
implementation 'com.google.android.material:material:1.6.1'