如果input.getText()
返回的长度大于 13,则用户输入的最后一个字符不应出现在编辑字段中。如果第 13 个字符是",",则程序应允许在","之后增加 2 个字符。这样,编辑字段的最大长度将为 16。
像这样限制编辑字段的文本宽度的选项是什么?
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";
}
我已经编写了一个简单的BorderedEditField
类来扩展EditField
。修改此类的方法protected 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;
}
}
}