activity_main.xml file
Step 1: Open activity_main.xml file and create an EditText using id editText.
html
<? 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:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText with id editText--> < EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Input" android:inputType="text"/> </ LinearLayout > |
Step 2: In activity_main.xml file add code to show a button. Final activity_main.xml file is
html
<? 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:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText with id editText--> < EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Input" android:inputType="text"/> <!--Button with id showInput--> < Button android:id="@+id/showInput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="show" android:backgroundTint="@color/colorPrimary" android:textColor="@android:color/white" /> </ LinearLayout > |
Step 3: Open MainActivity.kt file and get the reference of Button and EditText defined in the layout file.
// finding the button val showButton = findViewById<Button>(R.id.showInput) // finding the edit text val editText = findViewById<EditText>(R.id.editText)
Setting the on click listener to the button
showButton.setOnClickListener { }
Getting the text entered by user
val text = editText.text
Android EditText in Kotlin
EditText is used to get input from the user. EditText is commonly used in forms and login or registration screens. Following steps are used to create EditText in Kotlin:
- Add a EditText in activity_main.xml file.
- Add a Button in activity_main.xml file.
- Open MainActivity.kt file and set OnClickListener for the button to get the user input from EditText and show the input as Toast message.