Android Tutorials Hello Views

Hello, Views

This is a collection of "Hello World"-style tutorials designed to get you started quickly with common Android layouts and widgets.

Before you start, you should have completed the Android Tutorials Hello World.

Layouts

Linear Layout

LinearLayout is a ViewGroup that displays child View elements in a linear direction, either vertically or horizontally.

You should be careful about over-using the LinearLayout. If you begin nesting multiple LinearLayouts, you may want to consider using a RelativeLayout instead.

  • Start a new project named HelloLinearLayout.
  • Modify res/layout/main.xml file and insert the following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:layout_weight="1">
      <TextView
          android:text="red"
          android:gravity="center_horizontal"
          android:background="#aa0000"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="green"
          android:gravity="center_horizontal"
          android:background="#00aa00"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="blue"
          android:gravity="center_horizontal"
          android:background="#0000aa"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
      <TextView
          android:text="yellow"
          android:gravity="center_horizontal"
          android:background="#aaaa00"
          android:layout_width="wrap_content"
          android:layout_height="fill_parent"
          android:layout_weight="1"/>
  </LinearLayout>
 
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">
    <TextView
        android:text="row one"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row two"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row three"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:text="row four"
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
  </LinearLayout>
 
</LinearLayout>

Carefully inspect this XML. There is a root LinearLayout that defines its orientation to be vertical—all child Views (of which it has two) will be stacked vertically.

The first child is another LinearLayout that uses a horizontal orientation and the second child is a LinearLayout that uses a vertical orientation.

Each of these nested LinearLayouts contain several TextViewelements, which are oriented with each other in the manner defined by their parent LinearLayout.

HelloLinearLayout.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

Run the application, and you will see the layout.

References

  • LinearLayout
  • TextView

Relative Layout

RelativeLayout is a ViewGroup that displays child View elements in relative positions. The position of a View can be specified as relative to sibling elements (such as to the left-of or below a given element) or in positions relative to the RelativeLayout area (such as aligned to the bottom, left of center).

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested ViewGroups. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Type here:"/>
    <EditText
        android:id="@+id/entry"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_below="@id/label"/>
    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/entry"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"
        android:text="OK" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/ok"
        android:layout_alignTop="@id/ok"
        android:text="Cancel" />
</RelativeLayout>

Notice each of the android:layout_* attributes, such as layout_below, layout_alignParentRight, and layout_toLeftOf. When using a RelativeLayout, you can use these attributes to describe how you want to position each View. Each one of these attributes define a different kind of relative position. Some attributes use the resource ID of a sibling View to define its own relative position. For example, the last Button is defined to lie to the left-of and aligned-with-the-top-of the View identified by the ID ok (which is the previous Button).

All of the available layout attributes are defined in RelativeLayout.LayoutParams

Resources

  • RelativeLayout
  • RelativeLayout.LayoutParams
  • TextView
  • EditText
  • Button

Table Layout

TableLayout is a ViewGroup that displays child View elements in rows and columns.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">
 
    <TableRow>
        <TextView
            android:layout_column="1"
            android:text="Open..."
            android:padding="3dip" />
        <TextView
            android:text="Ctrl-O"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
 
    <TableRow>
        <TextView
            android:layout_column="1"
            android:text="Save..."
            android:padding="3dip" />
        <TextView
            android:text="Ctrl-S"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
 
    <TableRow>
        <TextView
            android:layout_column="1"
            android:text="Save As..."
            android:padding="3dip" />
        <TextView
            android:text="Ctrl-Shift-S"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
 
    <View
        android:layout_height="2dip"
        android:background="#FF909090" />
 
    <TableRow>
        <TextView
            android:text="X"
            android:padding="3dip" />
        <TextView
            android:text="Import..."
            android:padding="3dip" />
    </TableRow>
 
    <TableRow>
        <TextView
            android:text="X"
            android:padding="3dip" />
        <TextView
            android:text="Export..."
            android:padding="3dip" />
        <TextView
            android:text="Ctrl-E"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
 
    <View
        android:layout_height="2dip"
        android:background="#FF909090" />
 
    <TableRow>
        <TextView
            android:layout_column="1"
            android:text="Quit"
            android:padding="3dip" />
    </TableRow>
</TableLayout>

Notice how this resembles the structure of an HTML table. The TableLayout element is like the HTML <table> element;TableRow is like a <tr> element; but for the cells, you can use any kind of View element. In this example, a TextView is used for each cell. In between some of the rows, there is also a basic View, which is used to draw a horizontal line.

References

  • TableLayout
  • TableRow
  • TextView

Grid View

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.

In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a toast message will display the position of the image.

  • Find some photos you'd like to use, or download these sample images. Save the image files into the project's res/drawable/directory.
  • Modify res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>
  • Insert the following code to onCreate() Method
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));
 
    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

After the main.xml layout is set for the content view, the GridView is captured from the layout with findViewById(int). ThesetAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. TheImageAdapter is created in the next step.

To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a newAdapterView.OnItemClickListener. This anonymous instance defines the onItemClick() callback method to show a Toastthat displays the index position (zero-based) of the selected item (in a real world scenario, the position could be used to get the full sized image for some other task).

  • Create a new class called ImageAdapter that extends BaseAdapter
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
 
    public ImageAdapter(Context c) {
        mContext = c;
    }
 
    public int getCount() {
        return mThumbIds.length;
    }
 
    public Object getItem(int position) {
        return null;
    }
 
    public long getItemId(int position) {
        return 0;
    }
 
    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
 
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }
 
    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7
    };
}

First, this implements some required methods inherited from BaseAdapter. The constructor and getCount() are self-explanatory. Normally, getItem(int) should return the actual object at the specified position in the adapter, but it's ignored for this example. Likewise, getItemId(int) should return the row id of the item, but it's not needed here.

The first method necessary is getView(). This method creates a new View for each image added to the ImageAdapter. When this is called, a View is passed in, which is normally a recycled object (at least after this has been called once), so there's a check to see if the object is null. If it is null, an ImageView is instantiated and configured with desired properties for the image presentation:

o setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View—this ensures that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as appropriate.

o setScaleType(ImageView.ScaleType) declares that images should be cropped toward the center (if necessary).
o setPadding(int, int, int, int) defines the padding for all sides. (Note that, if the images have different aspect-ratios, then less padding will cause for more cropping of the image if it does not match the dimensions given to the ImageView.)

If the View passed to getView() is not null, then the local ImageView is initialized with the recycled View object.

At the end of the getView() method, the position integer passed into the method is used to select an image from themThumbIds array, which is set as the image resource for the ImageView.
All that's left is to define the mThumbIds array of drawable resources.

Try experimenting with the behaviors of the GridView and ImageView elements by adjusting their properties. For example, instead of using setLayoutParams(ViewGroup.LayoutParams), try using setAdjustViewBounds(boolean).

References

  • GridView
  • ImageView
  • BaseAdapter
  • AdapterView.OnItemClickListener

Tab Layout

List View

Widgets & Other Views

  • Date Picker
  • Time Picker
  • Form Stuff
  • Spinner
  • Auto Complete
  • Gallery
  • Google Map View
  • Web View

Other resources:

  • Layout - View class
  • Widget - Widget package
  • Code samples - Api Demos