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
EditTextby its correct ID causes crashes. - Not converting
Editabletext toStringbefore use leads to errors. - Using
android:inputTypeincorrectly 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:hintfor placeholder text. - Use
android:inputTypeto specify keyboard type (e.g., text, number, email). - Always convert
editText.texttoStringwithtoString(). - 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.