How to properly focus a text input element (auto keyboard pop-up)?
(As an aside, the documentation could use way more examples. This should be simple, but just isn't working…I'm sure it's me :))
var mainWindow = Titanium.UI.createWindow();
mainWindow.open({
fullscreen:"true"
});
var textfield = Titanium.UI.createTextField({
color:'#336699',
height:35,
top:50,
left:50,
width:250,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
mainWindow.add(textfield);
textfield.focus(); /* no error, doesn't focus */
// mainWindow.textfield.focus(); /* error */
I'm assuming I'm just not targeting the object correctly. Thoughts or tips?
Best,
Nate
5 Answers
-
I found an answer I believe works. Adding an "open" event listen for the window and firing the focus command on that event seems to work.
Detailed here: http://developer.appcelerator.com/question/17351/start-with-focus-on-a-textarea
-
Here's another way to do it. ..and yes it appears to be related to events in the creation of the textArea no fully consumed while the .focus() function jumps ahead of that queue and tries to focus on a control not fully created. So if you dynamically build a textarea well after the window was already opened, the window open event won't work. This below however will work. I tried it using AppEvents and those events appear to have a different priority that does not allow it to work. Events within the control however do appear to work. I'm guessing the fireEvent throws a message at the back of the queue, after all the open events get consumed, therefore the text.focus() is able to focus on a fully formed control. (at least that's my assumption)
text = Titanium.UI.createTextArea({}); win.add(text); text.addEventListener('customeventname', function() { text.focus(); }); text.fireEvent('customeventname');
Normally I would name the event something like 'setFocus', but I didn't want a noob to think it was a documented event… (something I would have done in the beginning of my Appcelerator exploration.)
-
Add this code it works great
var first = true; textArea.addEventListener('focus', function f(e){ if(first){ first = false; textArea.blur(); }else{ textArea.removeEventListener('focus', f); } });
-
This works!, i have various text areas on a tableview with custom controls.
Hope this help.
_textArea = Ti.UI.createTextArea({
top:0,
backgroundColor:'silver',
color: 'white',
font: {fontSize:18, fontWeight:'normal'},
keyboardType: Ti.UI.KEYBOARD_DEFAULT,
returnKeyType: Ti.UI.RETURNKEY_GO,
textAlign: 'left',
hintText : 'Escriba aqu\u00ed su respuesta',
width:300,
height : Ti.UI.FILL,
editable: true
});view.add(_textArea); var btnTeclado = Titanium.UI.createButton({ image : '/images/teclado.jpg', height : 40, width : 100, right :10, bottom :1 }); btnTeclado.addEventListener('click', function(evt){ first=true; this.parent.children[0].focus(); this.parent.fireEvent('customevent', { src:this.parent }); });
-
How about adding the textfield before opening the main window?