如何在顶部创建具有全屏宽度和标签的自定义Object ChoiceField

时间:2013-06-20 02:53:36

标签: blackberry

我是使用Java BlackBerry SDK进行开发的新手。

我想创建一个全屏宽度的自定义ObjectChoiceField,并在其左上角放置标签。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这是一种 hack ,但您可以通过以下方式实现此目的:

  1. ObjectChoiceField中的选项(字符串)添加空格,以便将它们分隔为全屏宽度。

  2. 只需将单独的LabelField添加到自定义ObjectChoiceField上方 的经理。

  3. 像这样:

       public class FullWidthChoiceField extends ObjectChoiceField {
    
          private Object[] _choices;  // cached for convenience
          private int _orientation;   // track device orientation
    
          public void setChoices(Object[] choices) {
             // TODO: this pixel value may need some tweaking!
             final int HBUFFER_PX = 62;
             int desiredWidth = Display.getWidth() - getPaddingLeft() - getPaddingRight()
                   - getMarginLeft() - getMarginRight() - HBUFFER_PX;
             Font font = getFont();         
             int advanceOfOneSpace = font.getAdvance(' ');
    
             for (int c = 0; c < choices.length; c++) {  
                String trimmedChoice = ((String)choices[c]).trim();
                // how wide is the text for this choice?          
                int advance = font.getAdvance(trimmedChoice);
                int numSpacesToPad = Math.max(0, (desiredWidth - advance) / advanceOfOneSpace);
                char[] pad = new char[numSpacesToPad];
                Arrays.fill(pad, ' ');
                choices[c] = new String(pad) + trimmedChoice;  // pad to left of choice
             }
    
             _choices = choices;
             super.setChoices(choices);
          }
    
          // only needed if your app supports rotation!
          protected void layout(int width, int height) {
             super.layout(width, height);
             if (_orientation != Display.getOrientation()) {
                // orientation change -> we must readjust the choice field
                _orientation = Display.getOrientation();
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                   public void run() {
                      setChoices(_choices);               
                   }
                });
             }
          }           
       }
    

    并在Screen中使用它:

       public ObjectChoiceScreen() {
          super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR);
    
          Object[] choices = new Object[] { "one", "two", "three" };
          ObjectChoiceField ocf = new FullWidthChoiceField();
          ocf.setChoices(choices);
    
          VerticalFieldManager vfm = new VerticalFieldManager();
          vfm.add(new LabelField("Label", Field.USE_ALL_WIDTH));  //  | DrawStyle.HCENTER));
          vfm.add(ocf);
          add(vfm);
       }
    

    导致

    enter image description here

    这要求您通过调用ocf.setChoices()而不是在构造函数中设置字段的选择。如果您愿意,您当然可以将其添加到自定义构造函数中。