Perfect — here's how to create a clean, reusable utility method to hide the keyboard across all activities or fragments, including ChatActivity.


✅ Step-by-Step: Make hideKeyboard a Reusable Utility


🔹 Step 1: Create a Kotlin File for Extensions

📄 KeyboardUtils.kt (create under com.seneca.dayamed.utils or your preferred utils package):

package com.seneca.dayamed.utils

import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.content.Context

fun Activity.hideKeyboard() {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    val view = currentFocus ?: View(this)
    imm.hideSoftInputFromWindow(view.windowToken, 0)
    view.clearFocus()
}

✅ This will work in any Activity. You can also extend this to Fragment or View if needed later.


🔹 Step 2: Use It in ChatActivity

In ChatActivity, update your setupRecyclerView() like this:

import com.seneca.dayamed.utils.hideKeyboard // 👈 Make sure to import it

private fun setupRecyclerView() {
    binding.recyclerView.apply {
        layoutManager = LinearLayoutManager(this@ChatActivity).apply {
            stackFromEnd = true
        }
        adapter = chatAdapter

        setOnTouchListener { _, _ ->
            hideKeyboard()
            false
        }
    }
}

✅ Benefits

  • ✔ Clean and reusable across any Activity

  • 📦 Centralized utility — easy to maintain

  • ✨ Extendable to Fragment.hideKeyboard()View.hideKeyboard(), etc.


Let me know if you want companion functions for Fragment or View as well!

Comments

Popular posts from this blog

Activity & Intent Interview question and Answer

A Reusable MVVM API Call Pattern in Jetpack Compose

Most Developers Build Offline-First Apps Wrong — Here's What They Miss with Room