Presentation is loading. Please wait.

Presentation is loading. Please wait.

Further android gui programming

Similar presentations


Presentation on theme: "Further android gui programming"— Presentation transcript:

1 Further android gui programming
David Sutton

2 WHAT WE WILL COVER IN THIS LECTURE
GridView Custom Adapters Dialogs and Toasts Images and ImageView Colour in Android

3 TODAY’S TASK Toast Dialog
A simple two player noughts and crosses (tic tac toe) app. Players take turns and place their marks in squares by clicking on them. If a player click on an occupied a square a “Toast” is displayed warning him that the move is illegal. When the game is over (a player has made a line, or all squares are occupied) an alert dialog is dispayed, giving the users the option of starting a new game Toast Dialog

4 PROBLEMS TO SOLVE Display data in a 2D Grid. Display images
Manage colours Display Toasts and dialogs

5 THE GRIDVIEW CLASS Data source (e.g Array or ArrayList) GridView
Adapter A B C D E F G H I A B C D E F G H I G H I A GridView works in the same way as a ListView, but displays its data in a rectangular grid.

6 ADDING A GRIDVIEW Drag from the Composite Area of the Palette
We will need to set the numColumns attribute to 3.

7 LAYOUT <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".OCO" > <GridView android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:numColumns="3" > </GridView> </RelativeLayout> This attribute sets the number of columns in the GridView

8 NOUGHTS AND CROSSES VERSION 1

9 SETTING UP A DATA SOURCE AND ADAPTER
public class OXOGame extends Activity { private String[] board = {"*","*","*","*","*","*","*","*","*",}; private ArrayAdapter<String> boardAdapter; private GridView boardGrid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_oxogame); boardGrid = (GridView) findViewById(R.id.board_grid); boardAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, board); boardGrid.setAdapter(boardAdapter); }

10 WHAT WE SHOULD SEE AT THIS POINT
A grid of nine asterisks is displayed, but they do not yet respond to mouse clicks.

11 MAKING THE APP RESPONSIVE
public class OXOGame extends Activity { private String[] board = {"*","*","*","*","*","*","*","*","*",}; private ArrayAdapter<String> boardAdapter; private GridView boardGrid; private int playerNo=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_oxogame); boardGrid = (GridView) findViewById(R.id.board_grid); Add a private field to record whose turn it is.

12 MAKING THE APP RESPONSIVE
OnItemClickListener boardListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (playerNo==1) { board[position]="X"; playerNo=2; } else{ board[position]="O"; playerNo=1; boardAdapter.notifyDataSetChanged(); }; boardGrid.setOnItemClickListener(boardListener); This code needs to be added to the OnCreate method of the main Activity Note that we adding an OnItemClickListener, not an OnClickListener

13 WHAT WE SHOULD SEE AT THIS POINT
The application should now respond to mouse clicks by changing the character in a cell when we click on it.

14 PROGRESS SO FAR The application we have created meets the requirements we set, except that… It looks a bit basic It doesn’t yet display the Toasts and Dialogs we wanted. We will leave the Toasts and Dialogs to one side for now, and see how we can improve the appearance of the app by customising the adapter we are using. To do this we need a little more detail on how adapters work…

15 ADAPTER CLASS HIERARCHY
When we construct an ArrayAdapter, we pass it a reference to a resource ID for a TextView. Each element in the data source is converted to ta String, and then a new instance of the TextView is created to display that text. These methods are abstract, which means that they must be overriden in subclasses. BaseAdapter getCount getItem getItemId getView The getView method returns a view that is used to display an individual cell It can return any kind of view, not just a TextView ArrayAdapter TextView getCount getItem getItemId getView

16 THREE WAYS TO CHANGE THE BEHAVIOUR OF AN ADAPTER
BaseAdapter We will explore methods (1) and (3) getCount getItem getItemId getView (3) Extend BaseAdapter and implement abstract methods. (1) Create a new TextView and associate it with an ArrayAdapter ArrayAdapter TextView MyAdapter getCount getItem getItemId getView getCount getItem getItemId getView (2) Extend ArrayAdapter class and override getView. MyArrayAdapter getView

17 NOUGHTS AND CROSSES VERSION 2
Now we will create a slightly more appealing version of the game, in which the cells are marked out in a different colour to the background. We won’t need to place asterisks in blank cells any more. We can see where they are because of the colour contrast. We will need to create our own TextView resource for the cells. In other words we are implementing solution (1) from the previous slide.

18 PROBLEMS TO BE SOLVED Represent colours in Android
Set the background colour of the cells and the grid. Create a custom TextView for the cells. Leave space between the cells so that the background colour of the grid can show through.

19 REPRESENTING COLOUR IN ANDROID
It is good practice to externalise colours into a separate XML resource file. This allows us to change the colour scheme of the application without modifying the files that describe layout and behaviour. <?xml version="1.0" encoding="utf-8"?> <resources> <color name="cell_colour">#FFFF00FF</color> <color name="grid_background">#FF0000FF</color> </resources>

20 REPRESENTING COLOUR IN ANDROID
There are several different ways of specifying colours in Android. We shall use 8 digit hexadecimal numbers with two digits for the opacity, and two digits each for the red, green, and blue components of the colour. <color name="cell_colour">#FFFF00FF</color> Opacity FF=completely opaque 00=completely transparent Red Green Blue

21 CREATING A COLOURS RESOURCE FILE
Right click on the values folder. Select “New->Android XML file”. Set the root element to be “resources”.

22 CREATING A NEW COLOUR

23 COLOUR RESOURCE FILE <?xml version="1.0" encoding="utf-8"?>
<resources> <color name="cell_colour">#FFFF00FF</color> <color name="grid_background">#FF0000FF</color> </resources>

24 CREATING A NEW TEXTVIEW RESOURCE
Right click on the layout folder and select New->Android XML file. Set the root element to be TextView.

25 OUR CUSTOM TEXTVIEW <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android= " android:layout_width="match_parent" android:layout_height="match_parent” android:gravity="center" android:minHeight="80sp" android:textSize="40sp" > </TextView> Text should be centred in cell Set minimum height of cell Fairly large text This is the colour resource we created earlier

26 MODIFICATIONS TO MAIN ACTIVITY CODE
We don’t need asterisks any more public class OXOGame extends Activity { private String[] board = {"","","","","","","","","",}; private ArrayAdapter<String> boardAdapter; private GridView boardGrid; private int playerNo=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_oxogame); boardGrid = (GridView) findViewById(R.id.board_grid); boardAdapter = new ArrayAdapter<String>(this, R.layout.cell_text, board); We are using our own custom TextView instead of the built in android.R.layout.simple_list_item_1

27 WHAT WE SHOULD SEE NOW

28 NOUGHTS AND CROSSES VERSION 3
Version of the game in which noughts, crosses, and blank squares are represented as images. Internally we will store the state of the game as an array of nine integers. Each element of the array can have the value 0,1, or 2 and these values are interpreted as follows: 0 -> display image of blank square 1->display image of cross 2->display image of nought

29 DESIGN OF SOLUTION BaseAdapter getCount getItem getItemId getView
Extend BaseAdapter and implement abstract methods. OXOActivity ImageAdapter GridView int[] board getCount getItem getItemId getView Adapter reads int values in board array and produces ImageView objects to display in GridView Store board state as an array of ints in main Activity class

30 PROBLEMS TO SOLVE Store and display images
Extend BaseAdapter class. Understand and implement its abstract methods.

31 THE IMAGEVIEW CLASS ImageView is a subclass of View that can be used to display drawable resources such as images. Drawable resources reside in the folders res/drawable-mdpi res/drawable-hdpi res/drawable-xhdpi res/drawable-ldpi These are intended to store separate resources for medium, high, extremely high, and low pixel density screens. If android cannot find an hdpi or ldpi resource it takes the mdpi one and scales accordingly. We shall use PNG images stored in the mdpi folder.

32 IMAGE FILES

33 ABSTRACT METHODS OF BASEADAPTER CLASS
getCount getView getItem getItemId OXOActivity ImageAdapter Returns size of board array int[] board getCount getView getItem getItemId Returns an ImageView representing appropriate image We need to implement these two methods, but we don’t need to worry about what they do

34 IMAGEADAPTER CLASS SLIDE 1
public class ImageAdapter extends BaseAdapter { private Context context; int[] board; public ImageAdapter(Context c, int[] board) { context = c; this.board = board; } @Override public int getCount() { return board.length;

35 IMAGEADAPTER CLASS SLIDE 2
@Override 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(context); imageView.setLayoutParams(new GridView.LayoutParams(120, 120)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); `imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } switch (board[position]) { case 1: imageView.setImageResource(R.drawable.cross); break; case 2: imageView.setImageResource(R.drawable.nought); break; default: imageView.setImageResource(R.drawable.blank); break; return imageView;

36 IMAGEADAPTER CLASS SLIDE 3
@Override public Object getItem(int arg0) { return null; } public long getItemId(int arg0) { return 0;

37 MODIFICATIONS TO MAIN ACTIVITY
public class OXOGame extends Activity { private int[] board = new int[9]; private ImageAdapter boardAdapter; private GridView boardGrid; private int playerNo=1; @Override protected void onCreate(Bundle savedInstanceState) { boardAdapter = new ImageAdapter(this,board); boardGrid.setAdapter(boardAdapter); OnItemClickListener boardListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { board[position]=playerNo; if (playerNo==1) { playerNo=2;} else{playerNo=1;} boardAdapter.notifyDataSetChanged();

38 WHAT WE SHOULD SEE NOW

39 ADDING TOASTS AND DIALOGS
A Toast is a simple message that pops up in front of the current view. It disappears after a predetermined time. Toasts are easy to create and useful when debugging programs. A Dialog is a small window that prompts the user to take a decision or make an action. A dialog is usually “modal”. That is to say that the user is required to interact with it before (s)he can proceed with anything else. Toast Dialog

40 ADDING A TOAST OnItemClickListener boardListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (board[position] == 0) { board[position] = playerNo; if (playerNo == 1) { playerNo = 2; } else { playerNo = 1; } boardAdapter.notifyDataSetChanged(); else { Toast toast = Toast.makeText(getApplicationContext(), "Can't do that", Toast.LENGTH_LONG); toast.show(); }; Text of Toast Duration of Toast

41 CREATING DIALOGS For an Activity to show a dialog you need to:
Call the Activity’s showDialog method with an integer parameter. Override the Activity’s onCreateDialog method so that it creates an appropriate dialog when passed that integer parameter. private static final int END_GAME_DIALOG=1; …. if (hasWon(1) || hasWon(2) || allCellsTaken()) { showDialog(END_GAME_DIALOG); } @Override public Dialog onCreateDialog(int id) { switch (id) { case END_GAME_DIALOG: Builder builder = new AlertDialog.Builder(this);

42 ALERT DIALOGS Title Action Buttons To create an Alert dialog we instantiate an AlertDialog and use it to associate DialogInterface.OnClickListener listeners with its action buttons. N.B. DialogInterface.OnClickListener is not the same class as the android.view.View.OnClickListener interface we have used in previous lectures.

43 CREATING AN ALERT DIALOG
@Override public Dialog onCreateDialog(int id) { switch (id) { case END_GAME_DIALOG: Builder builder = new AlertDialog.Builder(this); builder.setMessage("Game Over!"); builder.setCancelable(true); builder.setNegativeButton("New Game", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { for (int i = 0; i < board.length; i++) { board[i] = 0; } boardAdapter.notifyDataSetChanged(); playerNo=1; dialog.cancel(); }); …. Complete code is in practical sheet

44 SUMMARY A GridView displays a data source (e.g. an array) as a two- dimensional grid. An adapter converts the underlying data into View objects that are displayed in the grid. We can customise adapters by: Associating a custom TextView with an ArrayAdapter Extending ArrayAdapter Extending BaseAdapter Colours can be externalised as XML resources. An ImageView can be used to display a drawable resource. Toasts are simple pop-up messages Dialogs are modal windows requiring the user to make a decision or take an action.


Download ppt "Further android gui programming"

Similar presentations


Ads by Google