0

如果返回的长度input.getText()大于 13,则用户输入的最后一个字符不应出现在编辑字段中。如果第 13 个字符是“,”,则程序应允许在“,”之后增加 2 个字符。这样,编辑字段的最大长度将为 16。

像这样限制 EditField 的文本宽度的选项是什么?

input = new BorderedEditField();

input.setChangeListener(new FieldChangeListener() {             
    public void fieldChanged(Field field, int context) {
        if(input.getText().length() < 13)
            input.setText(pruebaTexto(input.getText()));
        else
            //do not add the new character to the EditField
    }
});

public static String pruebaTexto(String r){
    return r+"0";
}
4

1 回答 1

1

我编写了一个简单BorderedEditField的扩展类EditFieldprotected boolean keyChar(char key, int status, int time)此类的方法被修改,以便可以操纵EditField的默认行为。如果您发现此示例有帮助,那么您可以改进实现。

import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;

public final class MyScreen extends MainScreen {
    public MyScreen() {
        BorderedEditField ef = new BorderedEditField();
        ef.setLabel("Label: ");

        add(ef);
    }
}

class BorderedEditField extends EditField {
    private static final int MAX_LENGTH = 13;
    private static final int MAX_LENGTH_EXCEPTION = 16;

    private static final char SPECIAL_CHAR = ',';

    protected boolean keyChar(char key, int status, int time) {
        // Need to add more rules here according to your need.
        if (key == Characters.DELETE || key == Characters.BACKSPACE) {
            return super.keyChar(key, status, time);
        }
        int curTextLength = getText().length();
        if (curTextLength < MAX_LENGTH) {
            return super.keyChar(key, status, time);
        }
        if (curTextLength == MAX_LENGTH) {
            char spChar = getText().charAt(MAX_LENGTH - 1);
            return (spChar == SPECIAL_CHAR) ? super.keyChar(key, status, time) : false;
        }
        if (curTextLength > MAX_LENGTH && curTextLength < MAX_LENGTH_EXCEPTION) {
            return super.keyChar(key, status, time);
        } else {
            return false;
        }
    }
}
于 2012-09-18T13:19:38.997 回答