Here is a Kotlin example of how to listen to keyboard keys for example Enter Key.
import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import android.view.KeyEvent
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) // Replace with your layout
editText = findViewById(R.id.editText) // Replace with your EditText id
// Set up the listener for the Enter key press
editText.setOnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
// Perform your action here
val text = editText.text.toString()
Toast.makeText(this, "You entered: $text", Toast.LENGTH_SHORT).show()
// Clear the EditText
editText.setText("")
return@setOnKeyListener true
}
false
}
}
}
- Import necessary classes:
android.view.KeyEvent
for handling key events.android.widget.Toast
for displaying a simple message.
- Initialize the EditText:
- Get a reference to the EditText using
findViewById()
.
- Set up the listener:
- Use
editText.setOnKeyListener()
to attach a listener for key events. - Inside the listener:
- Check if the pressed key is
KeyEvent.KEYCODE_ENTER
and the action isKeyEvent.ACTION_DOWN
(key pressed, not released). - If it is, perform your desired action. In this example:
- Get the text from the EditText using
editText.text.toString()
. - Display a Toast message showing the entered text.
- Clear the EditText using
editText.setText("")
. - Return
true
to consume the event, preventing the Enter key from performing its default action (moving to the next line).
- Check if the pressed key is
- If the pressed key is not Enter or the action is not down, return
false
to let the system handle the event.