Skip to content

@Recycle callback and RecyclableEditText

Compare
Choose a tag to compare
@janishar janishar released this 16 Feb 19:49

@Recycle Addition To PlaceHolderView

It will provide the callback to the ViewItem when the ViewHolder containing that ViewItem is recycled. It can then be used to clean up views and data.

Example:

@Layout(R.layout.row_user)
public class UserDetailView {

    @View(R.id.et_user_name) 
    private EditText etUserName;

    private User user;
    private TextWatcher textWatcher;

    public UserDetailView(User user){
         this.user = user;
         textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int pos, int i1, int i2) {
                if (charSequence.toString().length() > 0) {
                    user.setName(charSequence.toString())
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
   }

    @Resolve
    private void onResolved() {
        etUserName.setText(user.getName());
        etUserName.addTextChangedListener(textWatcher);
    }

    @Recycle
    private void onRecycle() {
        etUserName.removeTextChangedListener(textWatcher);
    }
}

RecyclableEditText Widget

The EditText in Android don't allow to remove TextChangedListener if TextWatcher instance is not known. Thus when ViewHolder is recycled then it leads to addition of multiple listeners and causes unpredictable behavior.

RecyclableEditText provides two methods setTextChangedListener and removeTextChangedListener.

    etUserName.setTextChangedListener(new RecyclableEditText.OnTextChangeListener() {
            @Override
            public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
                // Do something
            }
        });