我已編碼的簡單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;
}
}
}
解釋一下你的問題。 – Rupak
如果input.getText()返回的長度大於13,則用戶輸入的最後一個字符不應出現在編輯字段中。清楚嗎? – Lucas
好的,如果我理解正確,那麼你需要一個EditField,它最多可以有13個字符,是嗎?如果是,那麼你可以使用'setMaxSize(int size)'。這也可以在使用'public EditField(String label,String initialValue,int maxNumChars,long style)'構造EditField實例時完成。有關更多信息,請查看API文檔,http://www.blackberry.com/developers/docs/6.0.0api/net/rim/device/api/ui/component/EditField.html,http://www.blackberry.com /developers/docs/6.0.0api/net/rim/device/api/ui/component/BasicEditField.html。 – Rupak