Anchoring and Centralizing
Anchoring and centralizing can be easily achieved by using RelativeLayout
. Consider main.xml
(see Listing 1
), which contains five Button views embedded within the
Observe the following attributes found in the various Button views:
- layout_alignParentLeft: This aligns the view to the left of the parent view.
- layout_alignParentRight: This aligns the view to the right of the parent view.
- layout_alignParentTop: This aligns the view to the top of the parent view.
- layout_alignParentBottom: This aligns the view to the bottom of the parent view.
- layout_centerVertical: This centers the view vertically within its parent view.
- layout_centerHorizontal: This centers the view horizontally within its parent view.
shows the activity when viewed in the portrait mode.
Figure 4. Portrait Mode: The image shows the activity in portrait mode.
Figure 5. Landscape Mode:. This is what it looks like when all views are aligned appropriately.
When the screen orientation changes to landscape mode, the four buttons are aligned to the four edges of the screen and the center button is centered in the middle of the screen with its width fully stretched (see Figure 5).
If you want to manually reposition each view in your activity when the screen orientation changes, use AbsoluteLayout
. Consider the following content in main.xml
<?xml version="1.0" encoding="utf-8"?>
Here, the activity has only one button view as shown in Figure 6
Figure 6. Solo: This shows the activity with one view.
Figure 7. Redone: The Button view is repositioned and resized when it is in landscape mode.
When the screen orientation changes to landscape mode, you might want to reposition the button view. In this case, you need to write some code to determine the current screen orientation the activity is in and then manually set the layout parameter of the view to reposition.
To see how this is done, use the code in Listing 2 in Orientation.java.
The above program first checks the current screen size and determines the orientation. It then creates a new LayoutParams object (containing the new position to locate the view) to be used by the Button view.
Figure 7 shows the application in actionthe Button view is repositioned and resized when the screen orientation changes to landscape mode.