Android Text Input Dialog With Inflated View (Kotlin)

fun showCreateCategoryDialog() {    val context = this    val builder = AlertDialog.Builder(context)    builder.setTitle("New Category")    // https://stackoverflow.com/questions/10695103/creating-custom-alertdialog-what-is-the-root-view    // Seems ok to inflate view with null rootView    val view = layoutInflater.inflate(R.layout.dialog_new_category, null)    val categoryEditText = view.findViewById(R.id.categoryEditText) as EditText    builder.setView(view);    // set up the ok button    builder.setPositiveButton(android.R.string.ok) { dialog, p1 ->        val newCategory = categoryEditText.text        var isValid = true        if (newCategory.isBlank()) {            categoryEditText.error = getString(R.string.validation_empty)            isValid = false        }        if (isValid) {            // do something        }        if (isValid) {            dialog.dismiss()        }    }    builder.setNegativeButton(android.R.string.cancel) { dialog, p1 ->        dialog.cancel()    }    builder.show();}

Content of R.layout.dialog_new_category

<?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:padding="@dimen/dialog_margin"
    android:orientation="vertical"
    >

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <android.support.design.widget.TextInputEditText
            android:id="@+id/categoryEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Name"
            />

    </android.support.design.widget.TextInputLayout>
</LinearLayout>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.