Tuesday, March 3, 2020

android kotlin - AlertDialog title text color size bold programmatically

MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.style.*
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        val context = this

        button.setOnClickListener {
            val builder = MaterialAlertDialogBuilder(context)

            val title = SpannableString("This is alert dialog title")

            // alert dialog title text color
            title.setSpan(
                ForegroundColorSpan(Color.parseColor("#DA1884")),
                0,
                title.length,
                0
            )

            // alert dialog bold title
            title.setSpan(StyleSpan(Typeface.BOLD),0,title.length,0)

            // alert dialog title font
            title.setSpan(TypefaceSpan("sans-serif-light"),0,title.length,0)

            // alert dialog underline title
            title.setSpan(UnderlineSpan(),0,title.length,0)

            // alert dialog title text size
            title.setSpan(RelativeSizeSpan(1.5F),0,title.length,0)

            // dialog title
            builder.setTitle(title)


            // dialog message
            builder.setMessage("This is an example 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:id="@+id/constraintLayout"
    tools:context=".MainActivity">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Show Dialog"
        android:backgroundTint="#3D2B1F"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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