Cannot stop virtual keyboard from opening programmatically when getfocus called


I'm using Android Studio and Kotlin. I have a call to set focus to an edittext on startup in the OnCreate(). When I make this call the virtual keyboard opens. I need to close it. I believe it has to do with delays while the app loads the main activity. There was other code I had to remove as it requires special libraries to control an internal barcode scanner. Its possible the simple code below will work without this extra code.


import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity(), BarcodeReader.BarcodeListener {

    private var barcodeTextView: TextView? = null
    private var barcodeEditView: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        barcodeTextView = findViewById(R.id.barcodetextbox)
        barcodeEditView = findViewById(R.id.editTextText)

        // Prevent the soft keyboard from appearing when the EditText gains focus
        barcodeEditView?.showSoftInputOnFocus = false
        
        // Force hide keyboard when focus is gained as an extra precaution
        barcodeEditView?.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as                    InputMethodManager
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }

        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
        }

        barcodeEditView?.showSoftInputOnFocus = false
        barcodeEditView?.requestFocus()
        barcodeEditView?.post {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(barcodeEditView!!.windowToken, 0)
        }

    }

    private fun hideKeyboard() {
        val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        barcodeEditView?.let {
            imm.hideSoftInputFromWindow(it.windowToken, 0)
        }
    }    
}
1
Sep 25 at 9:03 PM
User AvatarJames Peternel
#android#kotlin

No answer found for this question yet.