Поиск по этому блогу

понедельник, 29 июня 2015 г.

Phonegap prompt. How to set input type.

В HTML для обычного поля ввода задать, данные какого типа туда можно вводить, очень просто - достаточно задать атрибут "type".

Для ввода чисел
<input type="number" name="numberTextfield"/>

Для ввода телефона
<input type="tel" name="phoneTextfield"/>

Это же прекрасно работает и в Phonegap. Появляются соответствующие клавиатуры для ввода.

А вот как задать тип клавиатуры для поля ввода, которое будет в диалоге Prompt?

Вот документация по соответствующему плагину.
http://docs.phonegap.com/en/edge/cordova_notification_notification.md.html

navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
Эта функция позволяет нам показывать более кастомный dislog box. Можно задать многое - callback, заголовок, текст по умолчанию и даже текст на кнопках. Но нельзя задать тип клавиатуры.

Пример использования
// Show a custom prompt dialog
function showPrompt() {
    navigator.notification.prompt(
        'Please enter your name',  // message
        onPrompt,                  // callback to invoke
        'Registration',            // title
        ['Ok','Exit']              // buttonLabels
    );
}

Еще пример со встроенным callback
window.navigator.notification.prompt(
    new String(), // message
    function(answer) {
        if (answer.buttonIndex === 1) {
            // Ok
            var newcat = answer.input1;
            transaction.executeSql("INSERT INTO cat (Name) VALUES (?)", [newcat]);
        }
        else {
            // Exit
        }
    }, // callback
    "ADD CATEGORY", //title
    ["Ok", "Exit"], // button titles
    new String() // defaultText
);

Для того чтобы его настроить нам придется лезть в исходный код плагина и дополнять его.
plugins/CDVNotification.m

Нас интересует метод
- (void)prompt:(CDVInvokedUrlCommand*)command
{
    NSString* callbackId = command.callbackId;
    NSString* message = [command argumentAtIndex:0];
    NSString* title = [command argumentAtIndex:1];
    NSArray* buttons = [command argumentAtIndex:2];
    NSString* defaultText = [command argumentAtIndex:3];
 
    [self showDialogWithMessage:message title:title 
    buttons:buttons defaultText:defaultText 
    callbackId:callbackId dialogType:DIALOG_TYPE_PROMPT];
}

В нем вызывается другой метод
    title:(NSString*)title buttons:(NSArray*)buttons 
    defaultText:(NSString*)defaultText 
    callbackId:(NSString*)callbackId dialogType:(NSString*)dialogType {
 
CDVAlertView* alertView = [[CDVAlertView alloc]
    initWithTitle:title
              message:message
             delegate:self
    cancelButtonTitle:nil
    otherButtonTitles:nil];
 
alertView.callback
 
Id = callbackId;
 
    int count = [buttons count];
 
    for (int n = 0; n < count; n++) {
        [alertView addButtonWithTitle:[buttons objectAtIndex:n]];
    }
 
    if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) {
        UITextField* textField = [alertView textFieldAtIndex:0];
        textField.text = defaultText;
    }
 
    [alertView show];
}

Нам нужно задать полю ввода тип клавиатуры.
[textField setKeyboardType:UIKeyboardTypeNamePhonePad];

Все возможные типы клавиатур
typedef enum {
    UIKeyboardTypeDefault,                // Default type for the current input method.
    UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain active
    UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
    UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
    UIKeyboardTypeNumberPad,              // A number pad (0-9). Suitable for PIN entry.
    UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
    UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
    UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).
    UIKeyboardTypeDecimalPad,             // A number pad including a decimal point
    UIKeyboardTypeTwitter,                // Optimized for entering Twitter messages (shows # and @)
    UIKeyboardTypeWebSearch,              // Optimized for URL and search term entry (shows space and .)
 
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated
 
} UIKeyboardType;


воскресенье, 28 июня 2015 г.

How to execute task in Google App Engine

Запускать задачи на выполнение в Google App Engine можно следующим образом

Получаем дефолтную очередь задач и добавляем в нее нашу задачу.
Inline анонимный класс, который реализует интерфейс DeferredTask - это задача, которая будет выполнятся.

import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
 
...
 
Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder.withPayload(new DeferredTask() {
    @Override
    public void run() {
 
    }
}));

Можно вынести задачу в отдельный класс, в случае если она используется в нескольких местах.

import com.google.appengine.api.taskqueue.DeferredTask;
 
public class ExampleTask implements DeferredTask {
 
    public ExampleTask(String param1, String param2) {
 
    }
 
    @Override
    public void run() {
    }
}

Queue queue = QueueFactory.getDefaultQueue();
queue.add(TaskOptions.Builder.withPayload(new ExampleTask(param1, param2)));