Layout Inflater - jorgepascoPE/Kotlin-snippets GitHub Wiki
Instantiates a layout XML file into its corresponding android.view.View objects. It is never used directly. Instead, use android.app.Activity#getLayoutInflater() or Context#getSystemService to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.
In this page, we will overview the process of inflating a view for a dialogueView (A dialog is a small window that prompts the user to make a decision or enter additional information), when a button is clicked.
A dialog view might look similar to this
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="26dp"
android:text="Add Element"
android:textAlignment="center"
android:textSize="18sp"
tools:layout_editor_absoluteX="132dp"
tools:layout_editor_absoluteY="2dp" />
<EditText
android:id="@+id/addObjectNameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="18dp"
android:layout_marginLeft="18dp"
android:layout_marginRight="18dp"
android:ems="10"
android:hint="Element name"
android:inputType="textPersonName"
android:textColor="@android:color/darker_gray"
tools:layout_editor_absoluteX="49dp"
tools:layout_editor_absoluteY="16dp" />
<EditText
android:id="@+id/addObjectDescriptionTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="18dp"
android:layout_marginLeft="18dp"
android:layout_marginRight="18dp"
android:ems="10"
android:hint="Object description"
android:inputType="textPersonName"
tools:layout_editor_absoluteX="37dp"
tools:layout_editor_absoluteY="69dp" />
</LinearLayout>
import android.support.v7.app.AlertDialog
fun btnClicked(view: View) {
val builder = AlertDialog.Builder(context)
val dialogView = layoutInflater.inflate(R.layout.some_dialog_view, root)
builder.setView(dialogView)
.setPositiveButton("Add") { dialog: DialogInterface?, which: Int ->
val objectName = dialogueView.findByViewId<EditText>(R.id.addObjectName).text.toString()
val objectDescription = dialogueView.findByViewId<EditText>(R.id.addObjectDescription).text.toString()
// Do something with these variables
}
.setNegativeButton("Cancel") { _, _ -> //parameters for the lambda expression can be "_" as they're never used
}.show()
}