0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Use EditText in Android: Syntax and Example

In Android, EditText is a UI element that allows users to enter and edit text. You add it in your layout XML and access it in your activity code to get or set the text input.
๐Ÿ“

Syntax

The EditText element is added in an XML layout file with attributes like android:id to identify it, android:layout_width and android:layout_height to set its size, and android:hint to show a placeholder text.

In your Kotlin or Java code, you find the EditText by its ID and use methods like getText() or setText() to read or change the text.

xml
<EditText
  android:id="@+id/editText"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="Enter text here" />
Output
A text input field with placeholder text 'Enter text here' visible on screen.
๐Ÿ’ป

Example

This example shows a simple Android activity with an EditText and a Button. When you tap the button, the app reads the text from the EditText and shows it in a Toast message.

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

    val editText = findViewById<EditText>(R.id.editText)
    val button = findViewById<Button>(R.id.button)

    button.setOnClickListener {
      val input = editText.text.toString()
      Toast.makeText(this, "You typed: $input", Toast.LENGTH_SHORT).show()
    }
  }
}
Output
When the button is clicked, a small popup shows: 'You typed: [your input text]'.
โš ๏ธ

Common Pitfalls

  • Forgetting to cast or find the EditText by its correct ID causes crashes.
  • Not converting Editable text to String before use leads to errors.
  • Using android:inputType incorrectly can limit input unexpectedly.
  • Not handling empty input can cause app logic issues.
kotlin
/* Wrong way: */
val input = editText.text  // Editable, not String

/* Right way: */
val input = editText.text.toString()
๐Ÿ“Š

Quick Reference

Remember these key points when using EditText:

  • Use android:hint for placeholder text.
  • Use android:inputType to specify keyboard type (e.g., text, number, email).
  • Always convert editText.text to String with toString().
  • Validate input before using it.
โœ…

Key Takeaways

Add EditText in XML layout with an ID and hint for user input.
Access EditText in code using findViewById and convert text to String.
Use android:inputType to control the keyboard and input format.
Always validate and handle empty input to avoid errors.
Common mistakes include forgetting to convert Editable to String and wrong ID references.