The Absolute Layout Layout Manager

The layout managers discussed thus far implement specific but very different strategies for laying out the contents of a container. Android also offers a layout manager that allows you to specify the exact position for the controls in the container. This layout manager is called AbsoluteLayout (see Listing 4-33).

Listing 4-33. An XML Layout Using AbsoluteLayout <AbsoluteLayout android:layout_width="fill_parent" android:layout_height="fill_parent"

xmlns:android="http://schemas.android.com/apk/res/android" <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Username:" android:layout_x="50px" android:layout_y="50px" />

<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="160px" android:layout_y="50px" />

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Password:" android:layout_x="50px" android:layout_y="100px" />

<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="160px" android:layout_y="100px" />

</AbsoluteLayout>

The user interface generated from the layout in Listing 4-33 is shown in Figure 4-18.

epq □ sid« 2:42 am i

Common Controls

Username: Password:

-

Figure 4-18. A UI that uses the AbsoluteLayout layout manager

The user interface shown in Figure 4-18 is a familiar UI—we have used this in several of our previous examples. The difference is obviously in the XML layout. As shown in Listing 4-33, we define two TextView instances along with two EditText fields. But in this example we've specified the x-y coordinates of the controls, whereas we didn't do that in the previous examples.

Note that the screen-coordinate system used in Android defines (0,0) as the top-left corner of the screen. As you move to the right, the x coordinate increases. Similarly, as you move down, the y coordinate increases.

In our examples thus far, we have generated user interfaces with the XML layouts. Although this is the recommended approach, you don't have to do it this way. In fact, most of the time you'll have to mix XML layout with Java code to create UIs. AbsoluteLayout is a good candidate for this approach because you can dynamically calculate the location of controls. Listing 4-34 shows how you can position an image using AbsoluteLayout.

Listing 4-34. Using the AbsoluteLayout Programmatically public void onCreate(Bundle icicle) {

super.onCreate(icicle);

ImageView img = new ImageView(this);

imgsetImageResource(R.drawable.myimage);

AbsoluteLayout al = new AbsoluteLayout(this);

mContentView.addView(img, new AbsoluteLayout.LayoutParams( 50, // width 50, //height 0, //left 0); //top setContentView(al);

Listing 4-34 loads an image from the drawable resource folder and then positions it at (50,50). It then sets the content view of the activity to an AbsoluteLayout.

0 0

Post a comment