basic ui elements: android menus (basics)

47
1 Basic UI elements: Android Menus (basics) Marco Ronchetti Università degli Studi di Trento

Upload: others

Post on 03-Feb-2022

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Basic UI elements: Android Menus (basics)

1

Basic UI elements: Android Menus (basics)

Marco Ronchetti Università degli Studi di Trento

Page 2: Basic UI elements: Android Menus (basics)

2

Menu types Traditional menus are awkward on a small screen. ⇒  Three stages menus:

  Option Menu (< 3.0) / Action Bar (>=3.0)   Context Menu (< 3.0) / Contextual Action mode(>=3.0)   Popup Menu

Page 3: Basic UI elements: Android Menus (basics)

3

Option Menu The primary collection of menu items for an activity. •  actions that have a global impact on the app,

e.g."Search," "Compose email," and "Settings." On Android 2.3 or lower (API level 10), the options menu is called by pressing the Menu button. From Android 3.0, the Menu button is deprecated (some devices don't have it). On Android 3.0 and higher, items from the options menu are presented by the action bar as a combination of on-screen action items and overflow options.

Page 4: Basic UI elements: Android Menus (basics)

4

Option Menu - overflow

Overflow

The first visible portion is the icon menu, which holds up to six menu items. If your menu includes more than six items, Android places the sixth item and the rest into the overflow menu, which the user can open by selecting More.

You can support older versions of Android with an action bar. Source code of an example is here: http://developer.android.com/resources/samples/ActionBarCompat/index.html

From 3.0: By default, the system places all items in the action overflow, but you can ask to show them in the action bar.

Page 5: Basic UI elements: Android Menus (basics)

5

SimpleMenu

Page 6: Basic UI elements: Android Menus (basics)

6

Layout & Strings <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android:id="@+id/tf1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/output" /> </LinearLayout>

<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">This is Activity A1</string> <string name="app_name">SimpleMenu</string> <string name="output">no results yet...</string> </resources>

Page 7: Basic UI elements: Android Menus (basics)

7

add(int groupId, int itemId, int order, CharSequence title)

Method of the Menu class. Adds a new item to the menu. This item displays the given title for its label. •  groupId The group identifier that this item should

be part of. This can be used to define groups of items for batch state changes. Normally use NONE if an item should not be in a group.

•  itemId Unique item ID. Use NONE if you do not need a unique ID.

•  order The order for the item. Use NONE if you do not care about the order. See getOrder().

•  title The text to display for the item.

Page 8: Basic UI elements: Android Menus (basics)

8

SimpleMenu – A1 public class A1 extends Activity { int nClicks=0; protected void onCreate(Bundle icicle) {

super.onCreate(icicle); setContentView(R.layout.layout1); } public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); int base=Menu.FIRST;

MenuItem item1=menu.add(base,1,1,"Increase"); MenuItem item2=menu.add(base,2,2,"Decrease"); return true; } public boolean onOptionsItemSelected(MenuItem item) { TextView tf = (TextView) findViewById(R.id.tf1);

if (item.getItemId()==1) increase(); else if (item.getItemId()==2) decrease(); else return super.onOptionsItemSelected(item); tf.setText("Clicks :"+nClicks); return true; }

package it.unitn.science.latemar; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView;

private void increase() { nClicks++; } private void decrease() { nClicks--; }

}

Menu is created

Respond to a Menu event

Page 9: Basic UI elements: Android Menus (basics)

9

Calling Activities in other apps: Android Intents

Marco Ronchetti Università degli Studi di Trento

Page 10: Basic UI elements: Android Menus (basics)

10

Re-using activities When you create an application, you can assemble it from •  activities that you create •  activities you re-use from other applications. An app can incorporate activities from other apps. Yes, but how? By means of Intents These activities are bound at runtime: newly installed applications can take advantage of already installed activities

Page 11: Basic UI elements: Android Menus (basics)

11

Compare…

public static invokeMyApplication(Activity parentActivity) { String actionName= "com.myCompany.myApp.intent.action.MY_APP"; Intent intent = new Intent(actionName); parentActivity.startActivity(intent); }

new Intent(Context c, Class c);

new Intent(String s)

instead of

A symbolic reference (name)

An actual class

IMPLICIT

ESPLICIT

Page 12: Basic UI elements: Android Menus (basics)

12

Data

new Intent(String s, URI uri)

name

IMPLICIT

Pointer to the data to work on

EXAMPLES new Intent(Intent.ACTION_CALL, Uri.parse(“tel:0461-881500”); new Intent(Intent.ACTION_VIEW, Uri.parse(“http://latemar.science.unitn.it”); new Intent(Intent.ACTION_VIEW, Uri.parse("geo:50.123,7.1434?z=19"));

Page 13: Basic UI elements: Android Menus (basics)

13

Our code – IntentUtils - 1 package it.unitn.science.latemar; import android.app.Activity; import android.content.Intent; import android.net.Uri; public class IntentUtils { public static void invokeWebBrowser(Activity activity) {

Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://latemar.science.unitn.it")); activity.startActivity(intent);

} public static void invokeWebSearch(Activity activity) {

Intent intent=new Intent(Intent.ACTION_WEB_SEARCH, Uri.parse("http://www.google.com")); activity.startActivity(intent);

}

A string

Page 14: Basic UI elements: Android Menus (basics)

14

Our code – IntentUtils - 2 public static void dial(Activity activity) {

Intent intent=new Intent(Intent.ACTION_DIAL); activity.startActivity(intent);

}

public static void showDirections(Activity activity){ Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps? saddr=Bolzano&daddr=Trento") activity.startActivity(intent);

} }

Page 15: Basic UI elements: Android Menus (basics)

15

Our Code: IntentsActivity -1 package it.unitn.science.latemar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class IntentsActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv=new TextView(this); tv.setText("Push the menu button!"); setContentView(tv); } public boolean onCreateOptionsMenu(Menu menu){

super.onCreateOptionsMenu(menu); int base=Menu.FIRST; MenuItem item1=menu.add(base,1,1,"invokeWebBrowser-VIEW"); MenuItem item2=menu.add(base,2,2,"invokeWebBrowser-SEARCH"); MenuItem item3=menu.add(base,3,3,"showDirections"); MenuItem item5=menu.add(base,4,4,"dial"); return true;

}

Page 16: Basic UI elements: Android Menus (basics)

16

Our Code: IntentsActivity -2 public boolean onOptionsItemSelected(MenuItem item) {

System.err.println("item="+item.getItemId()); if (item.getItemId()==1) IntentUtils.invokeWebBrowser(this); else if (item.getItemId()==2) IntentUtils.invokeWebSearch(this); else if (item.getItemId()==3) IntentUtils.showDirections(this); else if (item.getItemId()==4) IntentUtils.dial(this); else return super.onOptionsItemSelected(item); return true;

} }

Page 17: Basic UI elements: Android Menus (basics)

17

Our App

Page 18: Basic UI elements: Android Menus (basics)

18

Our activities

Page 19: Basic UI elements: Android Menus (basics)

19

Google’s published intents

See http://developer.android.com/guide/appendix/g-app-intents.html

Page 20: Basic UI elements: Android Menus (basics)

20

Intent structure Marco Ronchetti Università degli Studi di Trento

Page 21: Basic UI elements: Android Menus (basics)

21

The full Intent structure Who will perform the action? •  Component name (can be unnamed) Which action should be performed? •  Action identifier (a string) Which data should the action act on ? •  Data The URI of the data to be acted on How we classify the action to be performed? •  Category A (usually codified) string. How do we directly pass data? •  Extras Key-value pairs for additional information that

should be delivered to the component handling the intent

How do we specify behavior modification? •  Flags Flags of various sorts.

Page 22: Basic UI elements: Android Menus (basics)

22

Examples of action/data pairs ACTION_VIEW content://contacts/people/1 •  Display information about the person whose identifier is "1". ACTION_DIAL content://contacts/people/1 •  Display the phone dialer with the person filled in. ACTION_VIEW tel:123 •  Display the phone dialer with the given number filled in. Note how

the VIEW action does what what is considered the most reasonable thing for a particular URI.

ACTION_DIAL tel:123 •  Display the phone dialer with the given number filled in. ACTION_EDIT content://contacts/people/1 •  Edit information about the person whose identifier is "1". ACTION_VIEW content://contacts/people/ •  Display a list of people, which the user can browse through.

Page 23: Basic UI elements: Android Menus (basics)

23

Standard Actions Identifiers ACTION_MAIN ACTION_VIEW ACTION_ATTACH_DATA ACTION_EDIT ACTION_PICK ACTION_CHOOSER ACTION_GET_CONTENT ACTION_DIAL ACTION_CALL ACTION_SEND ACTION_SENDTO ACTION_ANSWER ACTION_INSERT ACTION_DELETE ACTION_RUN ACTION_SYNC ACTION_PICK_ACTIVITY ACTION_SEARCH ACTION_WEB_SEARCH ACTION_FACTORY_TEST

Page 24: Basic UI elements: Android Menus (basics)

24

Publishing Activities: Intent Filters and resolution

Marco Ronchetti Università degli Studi di Trento

Page 25: Basic UI elements: Android Menus (basics)

25

intent-filter If we have an activity called MyActivity, using intents we can publish it, so that other apps can call it. Other apps can call it like this:

<activity android:name="MyActivity" android:label="@string/my_application_label"> <intent-filter> <action android:name=”com.myCompany.myApp.intent.action.MY_APP” /> </intent-filter> </activity>

public static invokeMyApplication(Activity parentActivity) { String actionName= "com.myCompany.myApp.intent.action.MY_APP"; Intent intent = new Intent(actionName); parentActivity.startActivity(intent); }

In the manifest

Page 26: Basic UI elements: Android Menus (basics)

26

Implicit intents and intent resolution In the absence of a designated target, the Android system must find the best component (or components) to handle the intent. It does so by comparing the contents of the Intent object to intent filters, structures associated with components that can potentially receive intents. Filters advertise the capabilities of a component and delimit the intents it can handle. If a component does not have any intent filters, it can receive only explicit intents. A component with filters can receive both explicit and implicit intents.

Page 27: Basic UI elements: Android Menus (basics)

27

Late binding

Implicit intent messaging is a facility for

late run-time binding

between components in the same or different applications.

Page 28: Basic UI elements: Android Menus (basics)

28

Resolution

10

Intents and Intent Filters

Intent Filters> Description of what intents an activity can handle> Activities publish their intent filters in a manifest file

> Upon invocation of startActivity(intent) the system looks at the intent filters of allinstalled applications

<intent-filter android:priority="0"><action android:name="android.intent.action.VIEW"/><category android:name="android.intent.category.DEFAULT"/><category android:name="android.intent.category.BROWSABLE"/><data android:scheme="geo"/>

</intent-filter>

Only three aspects of an Intent object are consulted when the object is tested against an intent filter: •  action •  data (both URI and data type) •  category

The extras and flags play no part in resolving which component receives an intent. Then, if the resolution doesn’t provide a unique result, the user is requested to make the final choice.

Page 29: Basic UI elements: Android Menus (basics)

29

How is resolution performed?

1) the filter must list the name specified for the Intent, or it should define NO action at all.

<activity android:name=".EmailManagingActivity”> <intent-filter . . . >     <action android:name="com.ex. SHOW_CURRENT" />     <action android:name="com.ex. SHOW_RECENT" />     <action android:name="com.ex. SHOW_PENDING" />     . . . </intent-filter> </activity>

Intent x=new Intent("com.ex. SHOW_RECENT" ); x.setData(Uri.parse(“mailto:[email protected]”)); x.addCategory(“CATEGORY_DEFAULT”);

Page 30: Basic UI elements: Android Menus (basics)

30

How is resolution performed?

2) For an intent to pass the category test, every category in the Intent object must match a category in the filter. . <activity android:name=".EmailManagingActivity”> <intent-filter . . . >     <action android:name="com.ex. SHOW_CURRENT" />     <action android:name="com.ex. SHOW_RECENT" />     <action android:name="com.ex. SHOW_PENDING" /> <category android:name="android.intent.category.DEFAULT" />    . . . </intent-filter> </activity>

Intent x=new Intent("com.ex. SHOW_RECENT" ); x.setData(Uri.parse(“mailto:[email protected]”)); x.addCategory(“CATEGORY_DEFAULT”);

NOTE: Android treats all implicit intents passed to startActivity() as if they contained at least one category: CATEGORY_DEFAULT.

Page 31: Basic UI elements: Android Menus (basics)

31

For details see http://developer.android.com/reference/android/content/Intent.html#CATEGORY_ALTERNATIVE

Standard Categories

Page 32: Basic UI elements: Android Menus (basics)

32

How is resolution performed?

3) The data is compared.

<activity android:name=".EmailManagingActivity”> <intent-filter . . . >     <action android:name="com.ex. SHOW_RECENT" />     <data android:mimeType="video/mpeg" android:scheme="http" . . . />     . . . </intent-filter> </activity>

Intent x=new Intent("com.ex. SHOW_RECENT" ); x.setData(Uri.parse(“mailto:[email protected]”)); x.addCategory(“CATEGORY_DEFAULT”);

Page 33: Basic UI elements: Android Menus (basics)

33

Data resolution rules

FILTER INTENT

Contains URI Has Data type Contains URI Has Data type

NO NO NO NO

YES NO Matches URI NO (*)

NO YES NO Matches D.T.

NO YES

has a content: or file: URI

Matches D.T.

YES YES Matches URI Matches D.T. (**)

An Intent passes a Filter if:

(*) and the data type cannot be inferred from the URI (**) or a matching data type can be inferred from the URI

Page 34: Basic UI elements: Android Menus (basics)

34

Finding out if an Intent can be resolved public boolean isIntentAvailable(Context context, String action) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(

intent, PackageManager.MATCH_DEFAULT_ONLY);

if (resolveInfo.size() > 0) { return true; } return false; }

Page 35: Basic UI elements: Android Menus (basics)

35

Other uses of Intents: services An Intent object is passed to Context.startService() to •  initiate a service •  deliver new instructions to an ongoing service.

An intent can be passed to Context.bindService() to •  establish a connection between with a target

service.

Page 36: Basic UI elements: Android Menus (basics)

36

Other uses of Intents: broadcast receivers

Intent objects passed to any of the broadcast methods (methods of the class Context) are delivered to all interested broadcast receivers. Android finds the appropriate activity, service, or set of broadcast receivers to respond to the intent, instantiating them if necessary. There is no overlap within these messaging systems: •  Broadcast intents are delivered only to broadcast

receivers, never to activities or services. •  An intent passed to startActivity() is delivered only to an

activity, never to a service or broadcast receiver, etc.

Page 37: Basic UI elements: Android Menus (basics)

37

Android Java packages Marco Ronchetti Università degli Studi di Trento

Page 38: Basic UI elements: Android Menus (basics)

38

Basic components android.app

  implements the Application model for Android

android.content   implements the concept of Content providers

android content.pm   Package manager: permissions, installed {packages,

services, provider, applications, components}

android.content.res   Access to resources

android.provider   Contacts, MediaStore, Browser, Setting

Page 39: Basic UI elements: Android Menus (basics)

39

GUI basics android.view

  Menu, View, ViewGroup + listeners

android.view.animation android.view.inputmethod

  Input methods framework

android.widget   UI controls derived from View (Button, Checkbox…)

android.gesture   create, recognize, load and save gestures

Page 40: Basic UI elements: Android Menus (basics)

40

Graphics android.graphics

  low level graphics tools such as canvases, color filters, points, and rectangles that let you handle drawing to the screen directly.

  Bitmap, Canvas, Camera (3D transformation, not the camera!) , Color, Matrix, Movie, Paint, Path, Rasterizer, Shader, SweepGradient, Typeface

android.graphics.drawable   variety of visual elements that are intended for display only, such as bitmaps

and gradients android.graphics.drawable.shapes android.opengl

  opengl-related utility classes, not the opengl! javax.microedition.khronos.opengles javax.microedition.khronos.egl javax.microedition.khronos.nio android.renderscript

  low-level, high performance means of carrying out mathematical calculations and 3D graphics rendering

Page 41: Basic UI elements: Android Menus (basics)

41

Text rendering android.text

  classes used to render or track text and text spans on the screen

android.text.method   Classes that monitor or modify keypad input.

android.text.style   Text styling mechanisms

android.service.textservice   Provides classes that allow you to create spell checkers

android.view.textservice   Use spelling checkers

Page 42: Basic UI elements: Android Menus (basics)

42

Database, Web and location android.database

  classes to explore data returned through a content provider. android.datebase.sqlite

  the SQLite database management classes that an application would use to manage its own private database. Applications use these classes to manage private databases.

android.webkit

  tools for browsing the web.

android.location   Address, Geocoder, Location, LocationManager,

LocationProvider com.google.android.maps

Page 43: Basic UI elements: Android Menus (basics)

43

Network and telephony android.net

  Socket-level network API - help with network access, beyond the normal java.net.* APIs.

android.net.wifi android.bluetooth android.nfc

  Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.

android.telephony

  monitoring the basic phone information, plus utilities for manipulating phone number strings, SMS

  CellLocation, PhoneNumberUtils, TelephonyManager android.telephony.gsm

  Obtain Cell location of GSM android.telephony.cdma

  Obtain Cell location of CDMA - CDMA2000 is a family of 3G mobile technology standards

Page 44: Basic UI elements: Android Menus (basics)

44

Media and speech android.media

  manage various media interfaces in audio and video   MediaPlayer, MediaRecorder, Ringtone, AudioManager, FaceDetector.

android.media.effect   apply a variety of visual effects to images and videos

android.hardware   support for hardware features, such as the camera and other sensors

android.drm   Digital right management

android.mtp   interact directly with connected cameras and other devices, using the

PTP (Picture Transfer Protocol)

android.speech   base class for recognition service implementations

android.speech.tts   Text to Speech

Page 45: Basic UI elements: Android Menus (basics)

45

General utilities android.utils

  date/time manipulation, base64 encoders and decoders, string and number conversion methods, and XML utilities.

android.sax   XML parsing

android.test

  A framework for writing Android test cases and suites

android.preference   manage application preferences and implement the preferences UI. Using these

ensures that all the preferences within each application are maintained in the same manner and the user experience is consistent with that of the system and other applications

android.os

  basic operating system services, message passing, and inter-process communication

  Binder (ipc), FileObserver (changes in files) Handler e Looper (for dealing with message threads), BatteryManager, PowerManager

Page 46: Basic UI elements: Android Menus (basics)

46

Still useful java packages java.lang (e subpackages) java.math java.net + javax.net java.io java.nio java.sql+javax.sql

  (android.database preferable if possible)

java.util

Page 47: Basic UI elements: Android Menus (basics)

47

Other still useful packages javax.crypto javax.security javax.xml org.w3c.dom org.xml.sax org.apache.http (e subpackages)