Android Tutorials: how to build AlertDialog in Kotlin Android 2019

Please visit our site: http://www.ikh4ever.com/. For more videos please subscribe our Youtube Channel here: iKh4ever Studio




MainActivity.kt

class MainActivity : AppCompatActivity() {

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

        btn_alert.setOnClickListener {

            val dialogBuilder = AlertDialog.Builder(this)

            dialogBuilder.setMessage("Do you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes", DialogInterface.OnClickListener { diaglog, i -> finish()
                })
                .setNegativeButton("Cancel",DialogInterface.OnClickListener { dialog, i -> dialog.cancel() })


            val alert = dialogBuilder.create()

            alert.setTitle("Alert Box for example")

            alert.show()

        }

    }

}

main_activity.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        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:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:id="@+id/btn_alert"
    android:text="Show alert dialog"
    android:layout_centerInParent="true"/>


</RelativeLayout>
Download Full Source Code Here:

Post a Comment

Previous Post Next Post