Understanding User Interface in Android – Part 3: More Views

In the previous article, you saw the various basic views such as the TextView, EditText, Button, and how you can use them in your Android applications. In this article, we shall continue our exploration of another three categories of views – Picker views, List views, and Display views. The views discussed include:

TimePicker view

DatePicker view

ListView view

Spinner view

Gallery view

ImageView

ImageSwitcher view

GridView view

Note: for all the examples in this article, you shall use the project created in the previous article.

Picker Views

Selecting date and time is one of the very common tasks you need to perform in a mobile application. Android supports this functionality through the TimePicker and DatePicker views.

TimePicker View

The TimePicker view allows users to select a time of the day, in either 24 hour mode or AM/PM mode.
Add a new file to the res/layout folder and name it as datetimepicker.xml and populate it with the following element:

Modify the ViewsActivity.java file to start the DateTimePickerExample activity:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

packagenet.learn2develop.AndroidViews;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

publicclassViewsActivityextendsActivity

{

/** Called when the activity is first created. */

@Override

publicvoidonCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

startActivity(newIntent(this,DateTimePickerExample.class));

}

}

Press F11 to debug the application on the Android emulator. Figure 1 shows the TimePicker view in action. You can use the numeric keypad on the device to change the hour and minute and click on the AM button to toggle between AM and PM.

Figure 1: The TimePicker view in action

Displaying the TimePicker View in a Dialog Window

You can also display the TimePicker view in a dialog. Modify the DateTimePickerExample.java file as shown below:

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

packagenet.learn2develop.AndroidViews;

import android.app.Activity;

import android.app.Dialog;

import android.app.TimePickerDialog;

import android.os.Bundle;

import android.widget.TimePicker;

import android.widget.Toast;

publicclassDateTimePickerExampleextendsActivity

{

inthour,minute;

staticfinalintTIME_DIALOG_ID=0;

@Override

protectedvoidonCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.datetimepicker);

showDialog(TIME_DIALOG_ID);

}

@Override

protectedDialog onCreateDialog(intid)

{

switch(id){

caseTIME_DIALOG_ID:

returnnewTimePickerDialog(

this,mTimeSetListener,hour,minute,false);

}

returnnull;

}

privateTimePickerDialog.OnTimeSetListener mTimeSetListener=

newTimePickerDialog.OnTimeSetListener()

{

publicvoidonTimeSet(TimePicker view,inthourOfDay,intminuteOfHour)

{

hour=hourOfDay;

minute=minuteOfHour;

Toast.makeText(getBaseContext(),

"You have selected : "+hour+":"+minute,

Toast.LENGTH_SHORT).show();

}

};

}

The above program displays the TimePickerDialog when the activity is created. When the time is set, the selected time is displayed using the Toast class. Figure 2 shows the TimePickerDialog in action.

Figure 2: The TimePickerDialog in action

DatePicker View

Like the TimePicker view, the DatePicker view allows users to select a date. Modify the datetimepicker.xml file as follows:

Press F11 to debug the application on the Android emulator. Figure 3 shows the DatePicker view in action. Besides touching the “+” and “-“ buttons, you can also use the numeric keypad on the device to change the month, day, and year.

Figure 3: The DatePicker view in action

Displaying the DatePicker View in a Dialog Window

You can also display the DatePicker view in a dialog. Modify the DateTimePickerExample.java file as shown below:

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

packagenet.learn2develop.AndroidViews;

import android.app.Activity;

import android.app.DatePickerDialog;

import android.app.Dialog;

import android.app.TimePickerDialog;

import android.os.Bundle;

import android.widget.DatePicker;

import android.widget.TimePicker;

import android.widget.Toast;

publicclassDateTimePickerExampleextendsActivity

{

inthour,minute;

intYear,month,day;

staticfinalintTIME_DIALOG_ID=0;

staticfinalintDATE_DIALOG_ID=1;

@Override

protectedvoidonCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.datetimepicker);

showDialog(DATE_DIALOG_ID);

}

@Override

protectedDialog onCreateDialog(intid)

{

switch(id){

caseTIME_DIALOG_ID:

returnnewTimePickerDialog(

this,mTimeSetListener,hour,minute,false);

caseDATE_DIALOG_ID:

returnnewDatePickerDialog(

this,mDateSetListener,Year,month,day);

}

returnnull;

}

privateTimePickerDialog.OnTimeSetListener mTimeSetListener=

newTimePickerDialog.OnTimeSetListener()

{

//...

};

privateDatePickerDialog.OnDateSetListener mDateSetListener=

newDatePickerDialog.OnDateSetListener()

{

publicvoidonDateSet(DatePicker view,intyear,intmonthOfYear,

intdayOfMonth)

{

Year=year;

month=monthOfYear;

day=dayOfMonth;

Toast.makeText(getBaseContext(),

"You have selected : "+(month+1)+

"/"+day+"/"+Year,

Toast.LENGTH_SHORT).show();

}

};

}

The above program displays the DatePickerDialog when the activity is created. When the date is set, the set date is displayed using the Toast class. Figure 4 shows the DatePickerDialog in action.

Figure 4: The DatePickerDialog in action

List Views

The ListView and Spinner views are useful for displaying long lists of items.

ListView View

The ListView view displays a list of items in a vertically scrolling list. To see how the ListView view works, add a new file to the res/layout folder and name it as listview.xml and populate it with the following element:

Modify the ViewsActivity.java file as follows to start the ListViewExample activity:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

packagenet.learn2develop.AndroidViews;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

publicclassViewsActivityextendsActivity

{

/** Called when the activity is first created. */

@Override

publicvoidonCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

startActivity(newIntent(this,ListViewExample.class));

}

}

Press F11 to debug the application on the Android emulator. Figure 5 shows the ListView view in action. When an item is selected, a message will be displayed.

Figure 5: The ListView view in action

Spinner View

The Spinner view displays an item at a time from a list and lets the users choose among them.
Add a new file to the res/layout folder and name it as spinner.xml and populate it with the following element:

Add a new file to the res/values folder and name it as attrs.xml. Populate it with the following:

<pre lang="xml" >

<?xml version="1.0"encoding="utf-8"?>

<resources>

<declare-styleable name="Gallery1 decode:true >

<attr name="android:galleryItemBackground" />

</declare-styleable>

</resources>

The Gallery1 style is used to apply to images displayed in the Gallery view so that the each image has a border around it (see Figure 9).

Figure 9: Gallery view, with borders on images

Add a few images to the res/drawable folder (see Figure 10).

Figure 10: Adding images

Add a new class to the src/net.learn2develop.AndroidViews folder and name it as DisplayViewsExample.java. Populate it as follows:

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

packagenet.learn2develop.AndroidViews;

importandroid.app.Activity;

importandroid.content.Context;

importandroid.content.res.TypedArray;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.widget.AdapterView;

importandroid.widget.BaseAdapter;

importandroid.widget.Gallery;

importandroid.widget.ImageView;

importandroid.widget.Toast;

importandroid.widget.AdapterView.OnItemClickListener;

publicclassDisplayViewsExampleextendsActivity

{

//---the images to display---

Integer[]imageIDs={

R.drawable.pic1,

R.drawable.pic2,

R.drawable.pic3,

R.drawable.pic4,

R.drawable.pic5,

R.drawable.pic6,

R.drawable.pic7

};

@Override

publicvoidonCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.displayview);

Gallery gallery=(Gallery)findViewById(R.id.gallery1);

gallery.setAdapter(newImageAdapter(this));

gallery.setOnItemClickListener(newOnItemClickListener()

{

publicvoidonItemClick(AdapterView parent,

Viewv,intposition,longid)

{

Toast.makeText(getBaseContext(),

"pic"+(position+1)+" selected",

Toast.LENGTH_SHORT).show();

}

});

}

publicclassImageAdapterextendsBaseAdapter

{

privateContext context;

privateintitemBackground;

publicImageAdapter(Contextc)

{

context=c;

//---setting the style---

TypedArraya=obtainStyledAttributes(R.styleable.Gallery1);

itemBackground=a.getResourceId(

R.styleable.Gallery1_android_galleryItemBackground,0);

a.recycle();

}

//---returns the number of images---

publicintgetCount(){

returnimageIDs.length;

}

//---returns the ID of an item---

publicObjectgetItem(intposition){

returnposition;

}

publiclonggetItemId(intposition){

returnposition;

}

//---returns an ImageView view---

publicView getView(intposition,View convertView,ViewGroup parent){

ImageView imageView=newImageView(context);

imageView.setImageResource(imageIDs[position]);

imageView.setScaleType(ImageView.ScaleType.FIT_XY);

imageView.setLayoutParams(newGallery.LayoutParams(150,120));

imageView.setBackgroundResource(itemBackground);

returnimageView;

}

}

}

You create the ImageAdapter class (which extends the BaseAdapter class) so that it can bind to the Gallery view with a series of ImageView views. The ImageView view is used to display images.
When an image in the Gallery view is selected (or clicked), the position of the image selected is displayed.
Modify the AndroidManifest.xml file to register the new activity:

Modify the ViewsActivity.java file as follows to start the DisplayViewsExample activity:

1

2

3

4

5

6

7

8

9

10

11

12

publicclassViewsActivityextendsActivity

{

/** Called when the activity is first created. */

@Override

publicvoidonCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

startActivity(newIntent(this,DisplayViewsExample.class));

}

}

Press F11 to debug the application on the Android emulator. Figure 11 shows the Gallery view in action. You can scroll through the list of thumbnail images by swiping it. When an image is selected, the name of the image selected will be displayed by the Toast class.

Figure 11: The Gallery view in action

If you want to display the selected image in an ImageView view, modify the onItemClick() method so that the selected image is shown in the ImageView (image1) view:

1

2

3

4

5

6

7

publicvoidonItemClick(AdapterView parent,

Viewv,intposition,longid)

{

//---display the images selected---

ImageView imageView=(ImageView)findViewById(R.id.image1);

imageView.setImageResource(imageIDs[position]);

}

When an image is selected, it will now be displayed in the ImageView view below (see Figure 12).

Figure 12: Selected image displayed in ImageView view

ImageSwitcher View

You saw in the previous section on how to use the Gallery view together with an ImageView view to display a series of thumbnail images so that when one is selected, the selected image is displayed in the ImageView view. Because this is such a common UI task, Android provides the ImageSwitcher view, which is functionally similar to what you have achieved in the previous section.

Modify the displayview.xml file as follows by adding the ImageSwitcher element:

Observe that the DisplayViewsExample class now implements the ViewFactory class. The ViewFactory class creates the views in a ViewSwitcher view. When your class implements the ViewFactory class, you need to override the makeView() method, which creates a new View to be added in a ViewSwitcher.
Press F11 in Eclipse and observe the ImageSwitcher in action as shown in Figure 13.

Figure 13: The ImageSwitcher in action

GridView View

The GridView view shows items in two-dimensional scrolling grid. You can use the GridView view together with ImageView views to display a series of images.

Modify the displayview.xml file as follows:

1

2

3

4

5

6

7

8

9

10

11

12

<?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:numColumns="auto_fit"

android:verticalSpacing="10dp"

android:horizontalSpacing="10dp"

android:columnWidth="90dp"

android:stretchMode="columnWidth"

android:gravity="center"

/>

In the DisplayViewsExample.java file, code the following:

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

packagenet.learn2develop.AndroidViews;

importandroid.app.Activity;

importandroid.content.Context;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.widget.AdapterView;

importandroid.widget.BaseAdapter;

importandroid.widget.GridView;

importandroid.widget.ImageView;

importandroid.widget.Toast;

importandroid.widget.AdapterView.OnItemClickListener;

publicclassDisplayViewsExampleextendsActivity

{

//---the images to display---

Integer[]imageIDs={

R.drawable.pic1,

R.drawable.pic2,

R.drawable.pic3,

R.drawable.pic4,

R.drawable.pic5,

R.drawable.pic6,

R.drawable.pic7

};

@Override

publicvoidonCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.displayview);

GridView gridView=(GridView)findViewById(R.id.gridview);

gridView.setAdapter(newImageAdapter(this));

gridView.setOnItemClickListener(newOnItemClickListener()

{

publicvoidonItemClick(AdapterView parent,

Viewv,intposition,longid)

{

Toast.makeText(getBaseContext(),

"pic"+(position+1)+" selected",

Toast.LENGTH_SHORT).show();

}

});

}

publicclassImageAdapterextendsBaseAdapter

{

privateContext context;

publicImageAdapter(Contextc)

{

context=c;

}

//---returns the number of images---

publicintgetCount(){

returnimageIDs.length;

}

//---returns the ID of an item---

publicObjectgetItem(intposition){

returnposition;

}

publiclonggetItemId(intposition){

returnposition;

}

//---returns an ImageView view---

publicView getView(intposition,View convertView,ViewGroup parent)

{

ImageView imageView;

if(convertView==null){

imageView=newImageView(context);

imageView.setLayoutParams(newGridView.LayoutParams(85,85));

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

imageView.setPadding(5,5,5,5);

}else{

imageView=(ImageView)convertView;

}

imageView.setImageResource(imageIDs[position]);

returnimageView;

}

}

}

Observe that the code is very similar to the Gallery view example – you create the ImageAdapter class (which extends the BaseAdapter class) so that it can bind to the GridView view with a series of ImageView views. The ImageView view is used to display images. When an image is selected, the position of the image is displayed using the Toast class.

Summary

In this article, you have seen the various views in the Picker, List and Display views category. Hopefully, you have a better understanding of them and are able to find a good use for them in your applications. Look out for the next article, where I will show you some menus and cool views you can use!

This is a website of Afilias Technologies Ltd, a private company limited by shares, incorporated and registered in the Republic of Ireland with registered number 398040 and registered office at 6th Floor, 2 Grand Canal Square, Dublin 2, Ireland