Skip to content

Instantly share code, notes, and snippets.

@antonyalkmim
Last active July 24, 2018 18:18
Show Gist options
  • Save antonyalkmim/0e66f4ae25217a1ce0dca0b245f494e3 to your computer and use it in GitHub Desktop.
Save antonyalkmim/0e66f4ae25217a1ce0dca0b245f494e3 to your computer and use it in GitHub Desktop.
Textfield masks on Appcelerator Titanium Android. Solution to stop infinite loops when changing value of a textfield inside your change listener on Appcelerator Titanium Android.
var changed = false;
$.texfield.addEventListener("change", function(e){
if(OS_IOS || (OS_ANDROID && !changed)){
e.source.value = "My Mask"; //Masker.toPatter();
}
changed = !changed;
//Set cursor at the end
var len = event.source.value.length;
$.textfield.setSelection(len, len);
});
@deckameron
Copy link

deckameron commented May 8, 2017

Hi antonyalkmim,

I have tried your approach on Android and iOS, but I could get it to work only on iOS. On Android, every time you "setSelection" it counts as new "change" event, therefore it goes into the infinite loop. The only way I could get it to work was this below.
I know it is not the most beautiful and well coded solution but it worked. :-)

var changeState = 0;
maskedTextField.addEventListener('change', function() {
    
    if(!this.value){
        return;
    }
    
    if(changeState == 0){
        Titanium.API.warn("Step 1 -> " + this.value);
        
        changeState = 1;
        maskedTextField.setValue(ApplyMask(this.value));
    }else{
        if(changeState == 1){
            Titanium.API.warn("Step 2 -> " + this.value);
            
            changeState = 2;
            var len = maskedTextField.getValue().length;
            maskedTextField.setSelection(len, len);
        }else{
            Titanium.API.warn("Step 3 -> " + this.value);
            
            changeState = 0;
        }
    }
});

@picoloto
Copy link

Hi deckameron,

This worked very well for me.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment