2012-09-17 19 views
0

如果input.getText()返回的長度大於13,則用戶輸入的最後一個字符不應出現在編輯字段中。如果第13個字符是',',程序應在','之後允許2個附加字符。這樣,編輯字段的最大長度將是16.BlackBerry - 從changeListener事件中設置EditField的文本寬度

什麼是限制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"; 
} 
+0

解釋一下你的問題。 – Rupak

+0

如果input.getText()返回的長度大於13,則用戶輸入的最後一個字符不應出現在編輯字段中。清楚嗎? – Lucas

+1

好的,如果我理解正確,那麼你需要一個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

回答

1

我已編碼的簡單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; 
     } 
    } 
} 
+0

謝謝Rupak! =) – Lucas

相關問題