I have hideKeyboard(view: View) method in util class. In my activity I want to call that method. I created object in activity utils = Utils() and then utils.HideKeyboard(binding.authConstraint) but when Im trying to click on constraintLayout it is throwing error "System services not available to Activities before onCreate()" what am I doing wrong ?
my Util Class
open class Utils():Activity(){
fun hideKeyboard(view: View) {
val inputMethodManager =
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
my activity
class AuthActivity : ActivityWithDisposableList() {
private lateinit var binding: ActivityAuthBinding
private lateinit var authViewModel: AuthViewModel
val utils = Utils()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_auth)
authViewModel = ViewModelProviders.of(this).get(AuthViewModel::class.java)
binding.authViewModel = authViewModel
binding.lifecycleOwner = this
authViewModel.isKeyboardClosed.observe(this, Observer { isTrue ->
if (isTrue) {
utils.hideKeyboard(binding.authConstraint,this)
binding.usernameInputEditText.clearFocus()
binding.passwordInputEditText.clearFocus()
}
})
}
}
CodePudding user response:
Do not create an instance of an Activity
subclass yourself. And do not make some arbitrary class extend Activity
, just because you need a Context
. Get the Context
from a parameter to a constructor or function.
With that in mind, replace your Utils
with:
class Utils {
fun hideKeyboard(view: View) {
val inputMethodManager =
view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
Here, you are getting the Context
from the View
that you are supplying.
Note that you could also go with object Utils
or have hideKeyboard()
be an extension function on View
, if you liked.