2013-02-09 52 views

回答

4

如果你真的想通過改變重寫paint()方法裏面的字體大小要做到這一點,你可以使用這樣的事情:

public TextScreen() { 
     super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR); 

     final int MAX_FONT_SIZE = 24; 
     // this is the font style to use, but the SIZE will only apply to the 
     // beginning of the text 
     Font f = Font.getDefault().derive(MAX_FONT_SIZE); 

     TextField text = new TextField(Field.NON_FOCUSABLE) { 
     public void paint(Graphics g) { 
      char[] content = getText().toCharArray(); 

      Font oldFont = g.getFont(); 
      int size = MAX_FONT_SIZE; 
      // use the baseline for the largest font size as the baseline 
      // for all text that we draw 
      int y = oldFont.getBaseline(); 
      int x = 0; 
      int i = 0; 
      while (i < content.length) { 
       // draw chunks of up to 3 chars at a time 
       int length = Math.min(3, content.length - i); 
       Font font = oldFont.derive(Font.PLAIN, size--); 
       g.setFont(font); 

       g.drawText(content, i, length, x, y, DrawStyle.BASELINE, -1); 

       // skip forward by the width of this text chunk, and increase char index 
       x += font.getAdvance(content, i, length); 
       i += length; 
      } 
      // reset the graphics object to where it was 
      g.setFont(oldFont); 
     }      
     }; 

     text.setFont(f); 
     text.setText("Hello, BlackBerry font test application!"); 

     add(text); 
    } 

注意,我不得不作出領域NON_FOCUSABLE,因爲如果你通過像這樣更改paint()中的字體來欺騙字段,藍色光標將與底層文本不匹配。您也可以通過覆蓋drawFocus()而不執行任何操作來刪除光標。

您沒有指定任何焦點要求,所以我不知道你想要什麼。

如果您願意考慮其他替代方案,我認爲RichTextField更適合讓您在相同字段中更改字體大小(或其他文本屬性)。如果你想要的只是逐漸縮小文本,就像我的例子那樣,這個paint()實現可能很好。如果您想在字段中選擇某些單詞以繪製更大的字體(如使用HTML <span>標籤),那麼RichTextField可能是最佳方式。

這裏是我的示例代碼的輸出:

enter image description here

相關問題