Demo: Autocomplete TextEdit

169 views
Skip to first unread message

Jorge Ramirez

unread,
Sep 3, 2014, 10:07:28 PM9/3/14
to androi...@googlegroups.com
Hi!

I was looking for a way to make autocompletion working on androidscript, there are a couple of libraries on JS but they usually work with a textfield in HTML.

Since our usecase is a little different (javascript inside android) I found another solution that makes a REGEX search in a javascript array and return an array of the possible match.

Then I made this example to stress test it with an array with 206 countries:

//Called when application is started.
function OnStart()
{
//Create a layout with objects aligned to the bottom of the screen.
lay = app.CreateLayout( "linear", "Bottom,FillXY" );
//create an empty list and set a function to trigger
//when an item is touched
    lst = app.CreateList( "", 0.8 );
    lst.SetOnTouch( lst_OnTouch );
    lay.AddChild( lst );

//Create a text edit, set a function to trigger on
//change, and add it to layout.
txt = app.CreateTextEdit( "Country",0.5 );
txt.SetTextSize( 32 );
txt.SetOnChange( txt_OnChange );
lay.AddChild( txt );
//Add layout to app.
app.AddLayout( lay );
}

//Triggered everytime the text edit
function txt_OnChange(){
    var text = txt.GetText().trim(); //get rid of trailing spaces with trim()
    
    if (text.length > 0){ //only act after the first character
        //here I set the list with the result of calling the 
        //matchCountries function with the text on txt
        lst.SetList( matchCountries( txt.GetText() ), "," ); 
    }
    else{
        //empty the list if I have less than one character
        lst.SetList("");
    }
}

//When an user touch an item on the list 
function lst_OnTouch( item ){
    //I write the touched item to the textedit
    txt.SetText( item );
    //I clear the list
    lst.SetList("");
}

//this is the function that I got on http://www.dustindiaz.com/autocomplete-fuzzy-matching
function matchCountries(input) {
  var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
  return countries.filter(function(country) {
    if (country.match(reg)) {
      return country;
    }
  });
}

//This is just the list of countries that it will filter
var countries = ['Afghanistan',
    'Albania',
    'Algeria',
    'Andorra',
    //...
    'Vietnam',
    'Yemen',
    'Zambia',
    'Zimbabwe'];

Download the SPK for the full list of countries!

I hope you find it useful!
Autocomplete.spk

Jorge Ramirez

unread,
Sep 3, 2014, 10:11:23 PM9/3/14
to androi...@googlegroups.com
I attach a couple of screenshots!
Screenshot_2014-09-03-23-10-07.png
Screenshot_2014-09-03-23-09-01.png

Schnee Wittchen

unread,
Sep 3, 2014, 11:47:18 PM9/3/14
to androi...@googlegroups.com
Hello Jorge,

not to bad, I really like it. I haven't tried it yet, but I like the concept.

Thanks for sharing.
best regards
Schnee
Reply all
Reply to author
Forward
0 new messages