airbnb / epoxy

Epoxy is an Android library for building complex screens in a RecyclerView
https://goo.gl/eIK82p
Apache License 2.0
8.51k stars 728 forks source link

Example of EditTextModel with TextWatcher #553

Open Xset-s opened 6 years ago

Xset-s commented 6 years ago

Could you please give an example of EditTextModel with listener (TextWatcher)?

Mradx commented 5 years ago

I have the same question. Please, could you give an example?

ghost commented 5 years ago

There are several examples in the following issues:

https://github.com/airbnb/epoxy/issues/426 https://github.com/airbnb/epoxy/issues/218

And one in MvRx: https://github.com/airbnb/MvRx/issues/115

shakil807g commented 5 years ago

I'm using it like this

 @ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
 class EditTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
 ) : FrameLayout(context, attrs, defStyleAttr) {

 init {
     inflate(context, R.layout.view_edittext, this)
 }

@CallbackProp
fun setOnChange(onChange: ((String) -> Unit)?) {
    editText.clearTextChangedListeners()
    editText.onChange { onChange?.invoke(it) }
}

@TextProp
fun setText(text: CharSequence?){
    editText.setTextAndCursorIfDiff(text)
}

@ModelProp
fun setError(error: String?) {
    inputLayout.error = error
}

@ModelProp
fun setHint(hint: String?) {
    inputLayout.hint = hint
}

@CallbackProp
fun setOnClick(onClick: (() -> Unit)?) {
    editText.setOnClickListener { onClick?.invoke() }
}

@ModelProp
fun setIcons(icons: Icons?) {
    icons?.let {
        val rightImg = context.resources.getDrawable(icons.right!!)
        rightImg.setBounds(0, 0, 50, 30)

        val leftImg = context.resources.getDrawable(icons.left!!)
        leftImg.setBounds(0, 0, 60, 60)

        editText.setCompoundDrawables(leftImg, null,rightImg,null)
    }

}

@OnViewRecycled
fun clear(){
    editText.clearTextChangedListeners()
}

data class Icons(val right: Int? = null,val left: Int?)

}

elihart commented 5 years ago

yes, there has been quite a lot of discussion and that you should be able to look at to get ideas, there are many ways you could approach it.

I do plan to write a more formal sample someday, if I ever have time.

@shakil807g in your code the clear method is not necessary

@OnViewRecycled
fun clear(){
    editText.clearTextChangedListeners()
}

this is because callback props are called with null to clear them when it is recycled, so this will be called with null

@CallbackProp
fun setOnChange(onChange: ((String) -> Unit)?) {
    editText.clearTextChangedListeners()
    editText.onChange { onChange?.invoke(it) }
}

which means your pattern for setting listeners would be better like


onChange?.let { editText.onChange(it) }