Meniu. Create a project:

Similar documents
Android Programs Day 5

Android Using Menus. Victor Matos Cleveland State University

Android Using Menus. Victor Matos Cleveland State University

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed.

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 4. Workshop

Vienos veiklos būsena. Theory

android:orientation="horizontal" android:layout_margintop="30dp"> <Button android:text="button2"

Android Specifics. Jonathan Diehl (Informatik 10) Hendrik Thüs (Informatik 9)

Mobila applikationer och trådlösa nät, HI1033, HT2013

Introducing the Android Menu System

Have a development environment in 256 or 255 Be familiar with the application lifecycle

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

Q.1 Explain the dialog and also explain the Demonstrate working dialog in android.

Mobila applikationer och trådlösa nät, HI1033, HT2012

Preferences. Marco Ronchetti Università degli Studi di Trento

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

Android Application Model I

Mobile Programming Lecture 7. Dialogs, Menus, and SharedPreferences

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

05. RecyclerView and Styles

Accelerating Information Technology Innovation

07. Menu and Dialog Box. DKU-MUST Mobile ICT Education Center

1. Simple List. 1.1 Simple List using simple_list_item_1

Action Bar. Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps.

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

Create Parent Activity and pass its information to Child Activity using Intents.

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015

Practical 1.ListView example

Managing Data. However, we'll be looking at two other forms of persistence today: (shared) preferences, and databases.

Embedded Systems Programming - PA8001

Intents. Your first app assignment

App Development for Smart Devices. Lec #7: Audio, Video & Telephony Try It Out

Arrays of Buttons. Inside Android

South Africa Version Control.

Thread. A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables.

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Our First Android Application

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Android HelloWorld - Example. Tushar B. Kute,

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Notification mechanism

ELET4133: Embedded Systems. Topic 15 Sensors

Basic GUI elements - exercises

Mobile and Ubiquitous Computing: Android Programming (part 3)

COMP4521 EMBEDDED SYSTEMS SOFTWARE

Programming with Android: Animations, Menu, Toast and Dialogs. Luca Bedogni. Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard.

Starting Another Activity Preferences

Android Workshop: Model View Controller ( MVC):

Let s take a display of HTC Desire smartphone as an example. Screen size = 3.7 inches, resolution = 800x480 pixels.

Android Beginners Workshop

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

<uses-permission android:name="android.permission.internet"/>

1. Location Services. 1.1 GPS Location. 1. Create the Android application with the following attributes. Application Name: MyLocation

Interface ใน View class ประกอบด วย

ActionBar. import android.support.v7.app.actionbaractivity; public class MyAppBarActivity extends ActionBarActivity { }

Solving an Android Threading Problem

CS 4330/5390: Mobile Application Development Exam 1

Lecture 14. Android Application Development

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

Database Development In Android Applications

Preferences. Marco Ronchetti Università degli Studi di Trento

User Interface Design & Development

App Development for Smart Devices. Lec #2: Activities, Intents, and User Interface

Android Data Storage

Android Navigation Drawer for Sliding Menu / Sidebar

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

Mobile Programming Lecture 2. Layouts, Widgets, Toasts, and Event Handling

UI, Continued. CS 2046 Mobile Application Development Fall Jeff Davidson CS 2046

android-espresso #androidespresso

ITU- FAO- DOA- TRCSL. Training on. Innovation & Application Development for E- Agriculture. Shared Preferences

Data Persistence. Chapter 10

TextView. A label is called a TextView. TextViews are typically used to display a caption TextViews are not editable, therefore they take no input

Programming with Android: Introduction. Layouts. Dipartimento di Informatica: Scienza e Ingegneria Università di Bologna

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

Manifest.xml. Activity.java

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

Tabel mysql. Kode di PHP. Config.php. Service.php

ANDROID USER INTERFACE

Getting Started With Android Feature Flags

Android Application Development. By : Shibaji Debnath

Overview. What are layouts Creating and using layouts Common layouts and examples Layout parameters Types of views Event listeners

App Development for Smart Devices. Lec #18: Advanced Topics

Android: Intents, Menus, Reflection, and ListViews

Embedded Systems Programming - PA8001

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Simple Currency Converter

5Displaying Pictures and Menus with Views

Multiple devices. Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers

Distributed Systems HS2010 Android live hacking

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.

Developed and taught by well-known Contact author and developer. At public for details venues or onsite at your location.

Topics of Discussion

Software Practice 3 Before we start Today s lecture Today s Task Team organization

ANDROID PROGRAMS DAY 3

UI (User Interface) overview Supporting Multiple Screens Touch events and listeners

Distributed Systems HS2011 Android live hacking

Produced by. Mobile Application Development. Eamonn de Leastar

Transcription:

Meniu Create a project: Project name: P0131_MenuSimple Build Target: Android 2.3.3 Application name: MenuSimple Package name: ru.startandroid.develop.menusimple Create Activity: MainActivity Open MainActivity.java. oncreateoptionsmenu method is responsible for creating a menu. Menu object is passed to this method as a parameter. We will add our menu items into this object. The adding procedure is simple, add method is used. This method takes the text of the menu item as a parameter. Let s add 4 items public boolean oncreateoptionsmenu(menu menu) { menu.add("menu1"); menu.add("menu2"); menu.add("menu3"); menu.add("menu4"); return super.oncreateoptionsmenu(menu); oncreateoptionsmenu method returns a boolean result. True - show menu, False - do not show. So we could have made a checking of some condition, and as a result of this check do not show a menu returning False. We don t need this for now, so we delegate this choice to the method of superclass, it returns True by default. Save everything, run the application and click the emulator menu button. Four menu items appeared. Clicking them will do nothing as listener is not implemented. Activity is a listener and method is called onoptionsitemselected. It receives menu item which has been clicked as a parameter - MenuItem. It is possible to define which menu item has been clicked by gettitle method. Let s show a Toast message with the text of the menu item clicked. Method must return a boolean value at the end. And we delegate it to the superclass again:

public boolean onoptionsitemselected(menuitem item) { Toast.makeText(this, item.gettitle(), Toast.LENGTH_SHORT).show(); return super.onoptionsitemselected(item); Complete code: public class MainActivity extends Activity { /** Called when the activity is first created. */ public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); public boolean oncreateoptionsmenu(menu menu) { menu.add("menu1"); menu.add("menu2"); menu.add("menu3"); menu.add("menu4"); return super.oncreateoptionsmenu(menu); public boolean onoptionsitemselected(menuitem item) { Toast.makeText(this, item.gettitle(), Toast.LENGTH_SHORT).show(); return super.onoptionsitemselected(item);

In the previous lesson we observed the simplest way of creating a menu using add(charsequence title) method, we passed only text as a parameter. Let s have a look at another implementation of this method - add(int groupid, int itemid, int order, CharSequence title). This methods takes 4 parameters: groupid - group identifier to which a menu item belongs to itemid - menu item ID order - for specifying the order in which menu items will be shown title - text that will be displayed We will create an application to illustrate how all these parameters are used. There will be a TextView and a CheckBox on the screen: - TextView will display which menu item was chosen - CheckBox will define whether to show a simple or expanded menu. It will be implemented using menu groups. Let me clarify that terms "simple menu" and "expanded menu" - are not Android terms, these are my namings. So when the application is running and the user clicks menu button, he will see a "simple" menu. If the user checks the CheckBox, the "expanded" menu which contains more items will be displayed. Let s create a project: Project name: P0141_MenuAdv Build Target: Android 2.3.3 Application name: MenuAdv Package name: ru.startandroid.develop.menuadv Create Activity: MainActivity Open main.xml, assign the ID to an existing TextView, erase text in it and create a CheckBox. Code: <?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"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/chbextmenu" android:text="expanded menu"> </CheckBox> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textview"> </TextView> </LinearLayout> Open MainActivity.java and fill in MainActivity class with the following code:

public class MainActivity extends Activity { // Screen elements TextView tv; CheckBox chb; /** Called when the activity is first created. */ public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); // find the elements tv = (TextView) findviewbyid(r.id.textview); chb = (CheckBox) findviewbyid(r.id.chbextmenu); // menu creation public boolean oncreateoptionsmenu(menu menu) { // adding menu items menu.add(0, 1, 0, "add"); menu.add(0, 2, 0, "edit"); menu.add(0, 3, 3, "delete"); menu.add(1, 4, 1, "copy"); menu.add(1, 5, 2, "paste"); menu.add(1, 6, 4, "exit"); return super.oncreateoptionsmenu(menu); // menu update public boolean onprepareoptionsmenu(menu menu) { // menu items with group ID = 1 are visible if CheckBox is checked menu.setgroupvisible(1, chb.ischecked()); return super.onprepareoptionsmenu(menu); // process clicks public boolean onoptionsitemselected(menuitem item) { StringBuilder sb = new StringBuilder(); // print the info about pressed menu item sb.append("item Menu"); sb.append("\r\n groupid: " + String.valueOf(item.getGroupId()));

sb.append("\r\n itemid: " + String.valueOf(item.getItemId())); sb.append("\r\n order: " + String.valueOf(item.getOrder())); sb.append("\r\n title: " + item.gettitle()); tv.settext(sb.tostring()); return super.onoptionsitemselected(item); Don t forget to update imports (CTRL + SHIFT +O). Let s look through the code above. We use the following methods: oncreateoptionsmenu - is invoked only when the menu is shown for the first time. Creates a menu and is not used any more. We add menu items here. onprepareoptionsmenu - invoked every time before displaying the menu. We make changes to the already existing menu if it is necessary. onoptionsitemselected - is invoked when the menu item is clicked. Here we define which menu item has been clicked. In the oncreateoptionsmenu we add 6 menu items. Have a look at the add method parameters. The first parameter is the group ID. For the first three items it equals 0, for the other three it equals 1. So the copy, paste and exit menu items are united into a group with ID = 1. Visually, it is not displayed in any way - they do not differ in color or something else. We will use group ID in onprepareoptionsmenu implementation. The second parameter is ID of menu item. It is used in listener to define which menu item has been pressed. We will use it in onoptionsitemselected. The third parameter defines the item position in the menu. This parameter is used for defining the order of menu items when it is displayed. The sort order is ascending, from smaller order to larger. The fourth parameter is text, which will be displayed on the menu item. Everything is clear with it. Menu object is passed to onprepareoptionsmenu method and we can work with it. In the current example we invoke setgroupvisible. This method allows to hide\show menu items. It is passed two parameters - group ID and a boolean value. We write 1 for the group ID (the same group which contains copy, paste and exit menu items). We will use thecheckbox state as a boolean parameter. If it is checked, menu items (from the group where ID = 1) will be displayed, if not - items will not be displayed. Let s save everything and launch the application. "Simple" menu:

"Expanded" menu

Depending on CheckBox state, 3 or 6 items in menu are visible. Pay attention to the item order. They are sorted by order parameter ascending. If the order of several items is the same, these items will be positioned in the order of their creation in oncreateoptionsmenu method. When pressing any menu item, onoptionsitemselected method is triggered. In this method we output the information about the item pressed to the TextView. You can compare this information to those we have coded when creating menu items. All the parameters have to match. I ve made the same order of items as in the add method for convenience: groupid, itemid, order, title. Try to add some more items to the menu and have a look how they are displayed. To simplify the code I ve hardcoded numbers for group IDs and menu item IDs. Usually, it is recommended to use constants. I will use constants further. XML-menu There is one more convenient and preferable way of creating a menu - using an xml-file, the same as layout-file when creating a screen. To get a menu which we have created programmatically in this lesson, we will create mymenu.xml file in res/menu folder: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item

android:id="@+id/menu_add" android:title="add"> </item> <item android:id="@+id/menu_edit" android:title="edit"> </item> <item android:id="@+id/menu_delete" android:orderincategory="3" android:title="delete"> </item> <group android:id="@+id/group1"> <item android:id="@+id/menu_copy" android:orderincategory="1" android:title="copy"> </item> <item android:id="@+id/menu_paste" android:orderincategory="2" android:title="paste"> </item> <item android:id="@+id/menu_exit" android:orderincategory="4" android:title="exit"> </item> </group> </menu> item - is a menu item, group - group of items. In the ID attributes we use the same approach as with IDs of screen components - @+id/<your_id> and Eclipse will generate these IDs in R.java. orderincategory attribute is the order of items, title is a text of menu item. Now we don t need to hardcode the creation of each menu item, we will just connect menu, which is passed as a parameter to the oncreateoptionsmenu method and our xml-file: public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.mymenu, menu); return super.oncreateoptionsmenu(menu); Using getmenuinflater method we obtain MenuInflater and invoke its inflate method. We pass our mymenu.xml file from res/menu folder and menu object as parameters. MenuInflater takes a menu object and fills it with menu items from mymenu.xml file. if you want to hide a group, invoke the same setgroupvisible method and pass R.id.group1 as a parameter for group ID. You can view attributes for menu xml-file in more details here. I recommend you to try and test both ways of creating a menu. Creating menu programmatically is more flexible, but xml shrinks the code amount.

Context menu in Android is invoked by long pressing any screen component. It is usually used in lists. When the list of similar objects is displayed (like messages in the mailbox) and you need to apply an action to one of these objects, a context menu is invoked for this object. But we didn t study lists yet, so we will make a simpler example and will invoke a context menu for TextView. Let s create a project: Project name: P0151_ContextMenu Build Target: Android 2.3.3 Application name: ContextMenu Package name: ru.startandroid.develop.contextmenu Create Activity: MainActivity Open main.xml and create two TextView objects there: <?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"> <TextView android:layout_height="wrap_content" android:textsize="26sp" android:layout_width="wrap_content" android:id="@+id/tvcolor" android:layout_marginbottom="50dp" android:layout_margintop="50dp" android:text="text color"> </TextView> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textsize="22sp" android:id="@+id/tvsize" android:text="text size"> </TextView> </LinearLayout> For the first TextView we will make a context menu using which we will change the text color. For the second we will change the text size. The way of creating a context menu is quite similar to creating a simple menu. But there are some differences. oncreatecontextmenu method is invoked every time before the menu is displayed. It is passed these parameters: - ContextMenu, into which we will add items - View - screen element, which the context menu is invoked for - ContextMenu.ContextMenuInfo - contains additional information, when the context menu is invoked for a list element. We don t use it for now, but when we will learn lists, we will see that it is useful.

oncontextitemselected process method is similar to onoptionsitemselected for a simple menu. MenuItem is passed as a parameter - it is a menu item that has been clicked. We will also need a third method registerforcontextmenu. It is passed View as a parameter and it means that context menu should be created for this View. If you do not invoke this method, context menu for a View will not be created. Lets code. Open MainActivity.java. Let s declare and find TextView and point out that context menu must be created for them. TextView tvcolor, tvsize; /** Called when the activity is first created. */ public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); tvcolor = (TextView) findviewbyid(r.id.tvcolor); tvsize = (TextView) findviewbyid(r.id.tvsize); // context menu should be created for tvcolor and tvsize registerforcontextmenu(tvcolor); registerforcontextmenu(tvsize); Now let s code the creation of context menus. We will use constants for storing menu item IDs. final int MENU_COLOR_RED = 1; final int MENU_COLOR_GREEN = 2; final int MENU_COLOR_BLUE = 3; final int MENU_SIZE_22 = 4; final int MENU_SIZE_26 = 5; final int MENU_SIZE_30 = 6; And create public void oncreatecontextmenu(contextmenu menu, View v, ContextMenuInfo menuinfo) { switch (v.getid()) { case R.id.tvColor: menu.add(0, MENU_COLOR_RED, 0, "Red"); menu.add(0, MENU_COLOR_GREEN, 0, "Green"); menu.add(0, MENU_COLOR_BLUE, 0, "Blue"); case R.id.tvSize:

menu.add(0, MENU_SIZE_22, 0, "22"); menu.add(0, MENU_SIZE_26, 0, "26"); menu.add(0, MENU_SIZE_30, 0, "30"); Pay attention that we define View for which context menu was invoked by its ID and depending on this ID, create a specific menu. So if context menu was invoked for tvcolor, we create a menu with colors enumeration, if for tvsize - enumeration with font sizes. We use constants as item IDs. We don t apply grouping or sorting, that s why we use zeros as corresponding parameters. Now you can save everything and run. When long pressing a TextView context menu should appear. But clicking on items does nothing as we haven t written processing in oncontextitemselected method. Let s fill it in: public boolean oncontextitemselected(menuitem item) { switch (item.getitemid()) { // menu items for tvcolor case MENU_COLOR_RED: tvcolor.settextcolor(color.red);

tvcolor.settext("text color = red"); case MENU_COLOR_GREEN: tvcolor.settextcolor(color.green); tvcolor.settext("text color = green"); case MENU_COLOR_BLUE: tvcolor.settextcolor(color.blue); tvcolor.settext("text color = blue"); // menu items for tvsize case MENU_SIZE_22: tvsize.settextsize(22); tvsize.settext("text size = 22"); case MENU_SIZE_26: tvsize.settextsize(26); tvsize.settext("text size = 26"); case MENU_SIZE_30: tvsize.settextsize(30); tvsize.settext("text size = 30"); return super.oncontextitemselected(item); In this method we define by ID which menu item has been clicked. And we do the corresponding actions afterwards: change the text color for tvcolor and font size for tvsize. Save, run and see that context menus now react to clicks and do what is required from them To broaden your horizons I would like to write something else about this topic. It may seem complicated for now, but it it s fine. So here are some thoughts. We have used registerforcontextmenu(view view) method for turning on context menu for a specific View. This method belongs to Activity class. I ve looked at the source code of this method. The following is written there: public void registerforcontextmenu(view view) { view.setoncreatecontextmenulistener(this); Remember our lesson (9) about listeners and have a look at help for setoncreatecontextmenulistener (View.OnCreateContextMenuListener l) method. It looks like View uses thisobject as listener for creating context menu. In this case, our code is inside Activity, so it means that this object is Activity. It means when a View wants to show a context menu, it refers to listener (Activity) and it invokes its oncreatecontextmenu method. So it is the similar concept as with a simple click.

And a line in MainActivity.java: registerforcontextmenu(tvcolor); is absolutely equal to this line: tvcolor.setoncreatecontextmenulistener(this); We can also create our own object that implements View.OnCreateContextMenuListener and use it instead of Activity as a listener for creating a context menu. Don t forget that you can also use XML-method to create a context menu, which we have reviewed at the end of the previous lesson. Try to complete the same lesson again, but using XML-menu this time. Complete lesson code: public class MainActivity extends Activity { final int MENU_COLOR_RED = 1; final int MENU_COLOR_GREEN = 2; final int MENU_COLOR_BLUE = 3; final int MENU_SIZE_22 = 4; final int MENU_SIZE_26 = 5; final int MENU_SIZE_30 = 6; TextView tvcolor, tvsize; /** Called when the activity is first created. */ public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); tvcolor = (TextView) findviewbyid(r.id.tvcolor); tvsize = (TextView) findviewbyid(r.id.tvsize); // context menu should be created for tvcolor and tvsize registerforcontextmenu(tvcolor); registerforcontextmenu(tvsize); public void oncreatecontextmenu(contextmenu menu, View v, ContextMenuInfo menuinfo) {

switch (v.getid()) { case R.id.tvColor: menu.add(0, MENU_COLOR_RED, 0, "Red"); menu.add(0, MENU_COLOR_GREEN, 0, "Green"); menu.add(0, MENU_COLOR_BLUE, 0, "Blue"); case R.id.tvSize: menu.add(0, MENU_SIZE_22, 0, "22"); menu.add(0, MENU_SIZE_26, 0, "26"); menu.add(0, MENU_SIZE_30, 0, "30"); public boolean oncontextitemselected(menuitem item) { switch (item.getitemid()) { // menu items for tvcolor case MENU_COLOR_RED: tvcolor.settextcolor(color.red); tvcolor.settext("text color = red"); case MENU_COLOR_GREEN: tvcolor.settextcolor(color.green); tvcolor.settext("text color = green"); case MENU_COLOR_BLUE: tvcolor.settextcolor(color.blue); tvcolor.settext("text color = blue"); // menu items for tvsize case MENU_SIZE_22: tvsize.settextsize(22); tvsize.settext("text size = 22"); case MENU_SIZE_26: tvsize.settextsize(26); tvsize.settext("text size = 26"); case MENU_SIZE_30: tvsize.settextsize(30); tvsize.settext("text size = 30"); return super.oncontextitemselected(item);