output
1/ Modify activity_main.xml
Add a mic_icon Vector Assets and Design - XML.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/mic"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginTop="204dp"
android:src="@drawable/mic_icon"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/speech_to_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:padding="10dp"
android:text="Voice to Text"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/mic" />
</androidx.constraintlayout.widget.ConstraintLayout>
2/ Modify MainActivity.kt
package com.zissofworks.voicetotextexampleandroidkotlin
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var mic: ImageView
private lateinit var speechToText: TextView
private val REQUEST_CODE_SPEECH_INPUT: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
mic = findViewById(R.id.mic)
speechToText = findViewById(R.id.speech_to_text)
mic.setOnClickListener {
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
)
intent.putExtra(
RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault()
)
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to text")
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && data != null) {
val result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
speechToText.text = result?.get(0) ?: ""
}
}
}
}