mdoery ~ software development

adventures in coding

android example using GridLayout

| Comments

Summary: I demonstrate building a simple app which uses android.support.v7.widget.GridLayout

I’m trying out a GridLayout for one of my projects. I built a small app to test it. The app looks like this on my tablet:

Here’s how to do it.

First, create an Android project in Eclipse (File > New > Project… > Android Application Project). In setting up my project I used a Minimum Required SDK of 2.2 (Froyo) and Target SDK 4.2 (Jelly Bean), and otherwise kept all the default settings proposed by Eclipse.

Next, import five image files into the res/drawable folder. These will be displayed in the grid. You can grab these images from this page (right-click on the image and “Save as…”). They are all in the public domain.

Open activity_main.xml in “Graphical Layout” view, click on “Layouts” and drag a “GridLayout” onto the view. A dialog opens which says “Warning android.widget.GridLayout requires API level 14 or higher, or a compatibility library for older versions. Do you want to install the compatibility library?” – do that. Set “Use Default Margins” to true, and set the “Column Count” to 2 (these two items are found under the Properties panel):

When I did this last step, something weird happened. I saw a couple of errors in the xml:

Unexpected namespace prefix “app” found for tag android.support.v7.widget.GridLayout. The activity_main.xml had the property app:columnCount=“2” – I hadn’t added this manually. I hunted around the internet and found a bug report about it, including a workaround – adding the attribute tools:ignore=“MissingPrefix” to the RelativeLayout tag gets rid of the error.

Finally, set the Android id for the GridLayout to be android:id=“@+id/gridLayout1”

The rest is simple; add all the images programmatically to the GridLayout, and it’s done. This is all the code that’s in my MainActivity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.mdoery.tut.gridlayout;

import android.os.Bundle;
import android.app.Activity;
import android.support.v7.widget.GridLayout;
import android.widget.ImageView;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      GridLayout gl = (GridLayout)findViewById(R.id.gridLayout1);
      setupGridLayout(gl);
  }

  private void setupGridLayout(GridLayout gl) {
      gl.addView(getImageView(R.drawable.apple));
      gl.addView(getImageView(R.drawable.ladybeetle));
      gl.addView(getImageView(R.drawable.moon));
      gl.addView(getImageView(R.drawable.sheep));
      gl.addView(getImageView(R.drawable.strawberry));
      
  }
  private ImageView getImageView(int resource) {
      ImageView iv = new ImageView(this);
      iv.setBackgroundResource(resource);
      return iv;
  }

}

Comments