Override layout()

  1. Import the required classes and interfaces.
    import net.rim.device.api.ui.component.ButtonField;
  2. In the screen constructor, create a new MyCustomButton object. The MyCustomButton class extends the ButtonField class and will provide a custom layout() method.
    MyCustomButton theButton = new MyCustomButton("Click me.");
  3. Add the MyCustomButton object to the screen.
    add(theButton);
  4. Create the MyCustomButton class.
    class MyCustomButton extends ButtonField
    {
  5. Implement a constructor for MyCustomButton to accept a String parameter. Invoke super() to invoke the constructor of the superclass, ButtonField, and set the String parameter as the label of the button.
        public MyCustomButton(String text)
        {
    		      super(text);
    	   }
  6. Implement layout() to specify custom layout instructions for MyCustomButton. In this task, layout() sets the size of the field to either 100 x 100 pixels or the maximum dimensions that are provided by the button's manager, whichever value is smaller.
        protected void layout(int width, int height)
     	  {
    		      setExtent(Math.min(100, width), Math.min(100, width));
    	   }
    }

Code sample: Overriding layout()

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.MainScreen;

import net.rim.device.api.ui.component.ButtonField;

public class OverridingLayoutDemo extends UiApplication
{
    public static void main(String[] args)
    {
        OverridingLayoutDemo theApp = new OverridingLayoutDemo();
    	   theApp.enterEventDispatcher();
    }
    
    public OverridingLayoutDemo()
    {
    	   pushScreen(new OverridingLayoutDemoScreen());
    }
}

class OverridingLayoutDemoScreen extends MainScreen
{
	   public OverridingLayoutDemoScreen()
	   {
		      setTitle("Overriding Layout Demo");
		
		      MyCustomButton theButton = new MyCustomButton("Click here.");
		
		      add(theButton);		
	   }
}

class MyCustomButton extends ButtonField
{
	   public MyCustomButton(String text)
	   {
		      super(text);
	   }
	
	   protected void layout(int width, int height)
 	  {
		      setExtent(Math.min(100, width), Math.min(100, width));
	   }
}

Was this information helpful? Send us your comments.