user14355661
user14355661

Reputation:

Adding 2 variables in a single TextUtils

I have this problem in which I have two variables - 'mobile_input' & 'mobile_input_login'. I also have 2 TextUtils also.

Instead of making two different TextUtils, I want to make one TextUtils. I have searched on the web but there is no relevant question like that.

The code:

mobile_input.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (TextUtils.isEmpty(s.toString().trim())) {
                clear2.setVisibility(View.INVISIBLE);

            } else {
                clear2.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
});


mobile_input_login.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (TextUtils.isEmpty(s.toString().trim())) {
                clear4.setVisibility(View.INVISIBLE);
            } else {
                clear4.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
});

Thank you for your answer in advance.

Upvotes: 0

Views: 23

Answers (1)

Nicolas
Nicolas

Reputation: 7081

You can create a custom class implementing TextWatcher:

public class MyTextWatcher implements TextWatcher {

    private View view;

    public MyTextWatcher(View view) {
        this.view = view;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (TextUtils.isEmpty(s.toString().trim())) {
            view.setVisibility(View.INVISIBLE);
        } else {
            view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

And then use it on both text fields:

mobile_input.addTextChangedListener(new MyTextWatcher(clear2));
mobile_input_login.addTextChangedListener(new MyTextWatcher(clear4));

I hope that answers your question.

Upvotes: 0

Related Questions