Jake
Jake

Reputation: 4255

Android Kotlin - disable EditText but DON'T hide keyboard

I have an EditText component for entering the text that will be sent via a POST request to a backend server. As it takes time to process the POST request and wait for a response, I want to disable the EditText input until the request is completed (and if successful, it then clears the text) for UX purposes.

I'm currently using

val smsMessageInput = findViewById<EditText>(R.id.smsMessageInput)
smsMessageInput.isEnabled = false

However this causes the keyboard to disappear, which isn't what I want to occur. How do I disable the input so the user can't enter text without hiding the keyboard?

I've also tried changing the text colour before the API call runs, however, this doesn't seem to work until AFTER the API call has completed. Here's the code:

smsMessageInput.setTextColor(ContextCompat.getColor(this, R.color.colorLowEmphasis))

Ideally, I would like to change the text colour of the EditText to a low-emphasis colour (the typical light-grey disabled colour that is widely used for disabled inputs on websites) and prevent the user from entering text in the EditText component.

Here's the full code I've tried without success:

    fun sendSms(smsToInput: EditText, smsMessageInput: EditText) {
        smsMessageInput.setTextColor(ContextCompat.getColor(this, R.color.colorLowEmphasis_Dark))
        smsMessageInput.isEnabled = false

        val formBody = FormBody.Builder()
            .add("to", smsToInput.text.toString())
            .add("message", smsMessageInput.text.toString())
            .build()
        val request = Request.Builder()
            .url("https://MYURL.com/POST_ROUTE")
            .post(formBody)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("Unexpected code $response")
            val body = response.body?.string()
            smsMessageInput.isEnabled = true
            smsMessageInput.text.clear()
            println(body)
        }
    }

Upvotes: 2

Views: 903

Answers (1)

ust
ust

Reputation: 171

I am using isFocusable instead of isEnabled for a similar purpose.

smsMessageInput.isFocusable = false

But anyway to show soft keyboard:

val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)

And you can requestFocus() in time you want.

Upvotes: 1

Related Questions