Home > database >  Text changed event not getting in Listener
Text changed event not getting in Listener

Time:10-01

I am using a Listener to be called when text gets changed. However to avoid stack overflow, I am removing and re-adding the text changed event. Unfortunately the function never gets called and the text never changes. What am I doing wrong here?

public TMP_InputField customTextField;

public void Start () {
        customTextField.onValueChanged.AddListener (TextChangedEvent);
    }

    public void TextChangedEvent (string newText) {
        customTextField.onValueChanged.RemoveListener (TextChangedEvent); //Remove Listener

        customTextField.text = newText.Replace ("0", "₀");
        customTextField.text = newText.Replace ("1", "₁");
        customTextField.text = newText.Replace ("2", "₂");

        customTextField.onValueChanged.AddListener (TextChangedEvent); //Add Listener back
    }

CodePudding user response:

First of all why assignt he text multiple times then everytime only replace again from the original text?

Currently either way you will only end up with

customTextField.text = newText.Replace ("2", "₂");

and throw away the results of your previous Replace operations.

You rather want to apply the Replace sequencially e.g. on the newText itself so you use the result of the first Replace call as input to the next one!

newText = newText.Replace ("0", "₀");
newText = newText.Replace ("1", "₁");
newText = newText.Replace ("2", "₂");

which of course you can also simply do in a single line

var replacedText = newText.Replace ("0", "₀").Replace ("1", "₁").Replace ("2", "₂");

And then note that there is TMP_InputField.SetTextWithoutNotify which does exactly what you want:

Set Input field's current text value without invoke onValueChanged

public void TextChangedEvent (string newText) 
{
    customTextField.SetTextWithoutNotify(newText.Replace ("0", "₀").Replace ("1", "₁").Replace ("2", "₂"));
}

Alternatively you could also already replace these symbols while the user is typing it using TMP_InputField.onValidateInput like e.g.

public TMP_InputField customTextField;

private void Start()
{
    customTextField.onValidateInput -= OnValidateInput;
    customTextField.onValidateInput  = OnValidateInput;
}

private void OnDestroy()
{
    customTextField.onValidateInput -= OnValidateInput;
}

private char OnValidateInput(string text, int charindex, char addedchar)
{
    switch (addedchar)
    {
        case '0':
            return '₀';

        case '1':
            return '₁';

        case '2':
            return '₂';

        default:
            return addedchar;
    }
}
  • Related