I need to create multiple editTexts
with logic to handle the format of the input. The different editTexts
will bind to different variables and save to different properties of viewModel.home
. The editTexts
will, however, use the same logic (although different for strings, ints, doubles, etc.) and thus I want to avoid copy-pasting code.
For each editText
I will have to set up an addTextChangedListener
and override the afterTextChanged
method (see below).
I want to generalize as much as possible through calling another method (customAfterTextChanged()
) from each of the overrides of afterTextChanged
:
viewBinding.editTextAdress.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
customAfterTextChanged()
}})
Some other places in the code I will define the method:
fun customAfterTextChanged () {
if (viewBinding.adressEditText.text.toString() != "") {
viewModel.home.adress = viewBinding.adressEditText.text.toString()
}
}
In the code above, home
and viewModel
are instances of custom classes, where home
exists as an instance within viewModel
.
My question now is: I want to be able to pass in, for example, viewBinding.cityEditText
instead of viewBinding.adressEditText
into the method. Or viewModel.home.city
instead of viewModel.home.adress
. To achieve this I think need to replace viewBinding.editTextAdress
and viewModel.home.adress
with method-specific variables, and somehow pass in references to for example viewModel.home.city
into the variables.
However, I can't wrap my head around how to do it. Can someone edit my code to make it work in this particular instance? I think I would then be able to translate to all the other logic if I can just get one working example.