How to set constant animation after EditText reach target length?

Viewed 20

I want to set animation on ImageView when user put more than 3 characters. I wrote a code to do this. Main problem is when I keep putting more than 3 characters the animation starts again from 0 position always when new character is added, so it doesn't looks good.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_user_first);

    initViews();
    imageButtonNext.setEnabled(false);

    horizontalScrollView.post(() -> horizontalScrollView.scrollTo(0, 0));
    horizontalScrollView.setOnTouchListener((v, event) -> true);

    editTextEnterName.addTextChangedListener(nameTextWatcher);

    pulse = AnimationUtils.loadAnimation(NewUserFirst.this, R.anim.pulse);

    imageButtonNext.setOnClickListener(view -> {
        intent = new Intent(this, NewUserSecond.class);
        startActivity(intent);
    });
}

public void buttonAnimation(){
    if(buttonBoolean){
        imageButtonNext.setAnimation(pulse);
        imageButtonNext.setColorFilter(ContextCompat.getColor(NewUserFirst.this, R.color.accent));
        imageButtonNext.setEnabled(true);
    } else {
        imageButtonNext.clearAnimation();
        imageButtonNext.setColorFilter(ContextCompat.getColor(NewUserFirst.this, R.color.gray));
        imageButtonNext.setEnabled(false);
    }
}

private final TextWatcher nameTextWatcher = new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        nameInput = editTextEnterName.getText().toString().trim();

        if (nameInput.length() >= 3) {
            buttonBoolean = true;
        } else {
            buttonBoolean = false;
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        buttonAnimation();
    }

};

So the question is, what changes I need to make in my code to set animation, and do not renew it every time when add next character.

1 Answers

Here is the answer:

public void buttonAnimation(){
    if(buttonBoolean){
        if (!imageButtonNext.isEnabled()) {
            imageButtonNext.setAnimation(pulse);
            imageButtonNext.setColorFilter(ContextCompat.getColor(this, R.color.accent));
            imageButtonNext.setEnabled(true);
        }
    } else {
        imageButtonNext.clearAnimation();
        imageButtonNext.setColorFilter(ContextCompat.getColor(this, R.color.gray));
        imageButtonNext.setEnabled(false);
    }
}

We need to add if statement in animation method. Program check animation is currently enabled, when yes, program do nothing. Result is animation triggered once live his own life until we modify edittext to length less than 3.

Related