Home > other >  How to use Inverse Binding Adapter in Kotlin for converting Lowercase text to Uppercase?
How to use Inverse Binding Adapter in Kotlin for converting Lowercase text to Uppercase?

Time:04-18

I am creating an android application where I want to use a feature in which a text that we have entered into an editText field can be converted into uppercase at runtime in that particular editText field only.

I have tried with this code

editText.addTextChangedListener(object : TextWatcher {
  override fun afterTextChanged(s: Editable?) {
  }

  override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
  }

  override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
     this.text.toString().uppercase()
  }
 })

But it can be easily done by the concept of Inverse Binding Adapter in android. I have tried to implement it with reference of https://developer.android.com/reference/android/databinding/InverseBindingAdapter

It is not working for me in my project. Can You explain me with step by step explanation?

CodePudding user response:

Yess This Method of addTextChangedListener is available but we have to implement this method for each and every Edittext we want to convert to Upper case. So you heard correct about the InverseBinding Adapter. In InverserBinding Adapter we have to create this method for one time and you can use it any number of time.

I have implemented this using BindingAdapter and InverseBinding Adapter.In one Kotlin File, Write this two functions as follows. Function Code

@BindingAdapter(value = ["setText", "custom:AttrChanged"], requireAll = false)
fun EditText.updateText(text: String?, listener: InverseBindingListener) {
    if (this.text.toString() != text) {
        this.setText(text)
    }
    this.doOnTextChanged { _: CharSequence?, _: Int?, _: Int?, _: Int? ->
        listener.onChange()
    }
}

@InverseBindingAdapter(attribute = "setText", event = "custom:AttrChanged")
fun EditText.getUpdatedText(): String? {
    return this.text.toString().uppercase()
}

For Upper Case I have created one uppercase variable of MutableLiveData of type String

var uppercase = MutableLiveData("")

Now in XML i have set that property as follow:

<androidx.appcompat.widget.AppCompatEditText
        android:id="@ id/edit_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="30dp"
        setText="@={viewModels.uppercase}"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_login_data_binding" />
  • Related