Size: px
Start display at page:

Download ""

Transcription

1 Menus, themes and ActionBar Activity communication and Bundle Shared Preferences Event handling More GUI components and Adapters

2 Menus OptionsMenu The main menu for an Activity that displays when the overflow button is pressed. It contains a text menu possibly with icons and an expanded menu when the more menu item is selected. Old devices may have a menu button Some very old apps only have the old menu (long press back button to open...) App Bar (Toolbar or ActionBar) Enables a consistent way for implementing actions and navigation ActionBar can be used from API 11 (from API 7 with v7 appcompat library) ToolBar can be used from API 21 (also from API 7 with v7 appcompat library) ContextMenu A floating list of menu items that displays when a specific Widget/View is long pressed SubMenu A floating list of menu items that displays when a menu item is pressed These types of menus should be made in XML They should be put in the app/res/menu/ resources directory See the BuildingMenus and ActionBar example

3 OptionsMenu with Java public boolean oncreateoptionsmenu(menu menu) { super.oncreateoptionsmenu(menu); // Create and add new menu alternatives // add (int groupid, int itemid, int order, CharSequence title) MenuItem itemabout = menu.add(menu.none, VIEW_ABOUT, Menu.NONE, getstring(r.string.about)); MenuItem itemdonothing = menu.add(menu.none, SOMETHING_ELSE, Menu.NONE, R.string.do_nothing); // Add icons itemabout.seticon(r.drawable.icon); // Add numeric and alphabetic shortcuts itemabout.setshortcut('0', 'o'); // about itemdonothing.setshortcut('1', 'i'); // nothing return true; public boolean onoptionsitemselected(menuitem item) { super.onoptionsitemselected(item); switch (item.getitemid()) { case (VIEW_ABOUT): { Intent aboutintent = new Intent(this, AboutActivity.class); startactivity(aboutintent); // start the new Activity return true;... Old style

4 OptionsMenu etc. in XML public boolean oncreateoptionsmenu(menu menu) { super.oncreateoptionsmenu(menu); // Returns a MenuInflater with this context MenuInflater inflater = getmenuinflater(); // Inflate a menu hierarchy from the specified XML resource inflater.inflate(r.menu.my_menu, menu); return true; XML code in /res/menu/my_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android=" > <item android:id="@+id/menu_about" android:title="@string/menu_about" android:icon="@drawable/icon" /> <item android:id="@+id/menu_do_nothing" android:title="@string/menu_do_nothing" </menu>

5 ContextMenu and SubMenu private String[] choices = {"Press Me", "Try Again", "Change Me"; public void oncreate(bundle savedinstancestate) {... bv = (TextView) findviewbyid(r.id.focus_text); registerforcontextmenu((view) findviewbyid(r.id.focus_text)); XML alt. in BuildingMenus example public void oncreatecontextmenu(contextmenu menu, View v, ContextMenuInfo menuinfo) { super.oncreatecontextmenu(menu, v, menuinfo); if(v.getid() == R.id.focus_text) { SubMenu textmenu = menu.addsubmenu("change Text"); textmenu.add(0, ID_TEXT1, 0, choices[0]); textmenu.add(0, ID_TEXT2, 0, choices[1]); textmenu.add(0, ID_TEXT3, 0, choices[2]); menu.add(0, ID_DEFAULT, 0, "Original Text"); Long press the textview to run oncreatecontextmenu ContextMenu and SubMenu is created and showed public boolean oncontextitemselected(menuitem item) { switch(item.getitemid()) { case ID_DEFAULT: bv.settext(r.string.hello); return true; case ID_TEXT1: case ID_TEXT2: case ID_TEXT3: bv.settext(choices[item.getitemid()-1]); return true; return super.oncontextitemselected(item);

6 App Bar (ActionBar or Toolbar) The App Bar

7 ActionBar Read:

8 OptionsMenu with ActionBar public boolean oncreateoptionsmenu(menu menu) { MenuInflater inflater = getmenuinflater(); inflater.inflate(r.menu.activity_main, menu); return super.oncreateoptionsmenu(menu); <uses-sdk android:minsdkversion="11" android:targetsdkversion="10" /> <activity android:parentactivityname="parentactivity"> </activity> <menu xmlns:android=" > <item android:id="@+id/menu_hide_navigation" android:orderincategory="100" android:icon="@drawable/robot48" android:title="@string/menu_hide_navigation" android:showasaction="ifroom withtext"/> <item android:id="@+id/menu_actionbar_toggle" android:orderincategory="100" android:showasaction="never" android:title="@string/menu_actionbar_toggle" /> </menu> public boolean onoptionsitemselected(menuitem item) { ActionBar actionbar = getactionbar(); switch (item.getitemid()) { case android.r.id.home: // an app icon in action bar when clicked - go to parent - since API 16 handled by parentactivityname in the AndroidManifest file // Intent intent = new Intent(this, ParentActivity.class); // intent.addflags(intent.flag_activity_clear_top Intent.FLAG_ACTIVITY_SINGLE_TOP); // startactivity(intent); NavUtils.navigateUpTo(this, new Intent(this, ActionBarExample.class)); return true; case R.id.menu_actionbar_toggle: if(visible) actionbar.hide(); else actionbar.show(); visible =!visible; return true; case R.id.menu_hide_navigation: getwindow().getdecorview().setsystemuivisibility(view.system_ui_flag_hide_navigation); return true; default: return super.onoptionsitemselected(item); Remove the Menu button in an AVD? Set hw.mainkeys=no in the config.ini file

9 Style, themes and resources By adding custom names in the res/values/styles.xml file your app can have a dark or light theme Icons can be XML programmed to automatically change Get icons: > Design > Downloads <style name="customthemelight" parent="android:theme.holo.light"> <item name="theme_dependent_icon_upload" >@drawable/ic_action_upload_light</item> <item name="theme_dependent_icon_share" >@drawable/ic_action_share_light</item> </style> <style name="customthemedark" parent="android:theme.holo"> <item name="theme_dependent_icon_upload" >@drawable/ic_action_upload_dark</item> <item name="theme_dependent_icon_share" >@drawable/ic_action_share_dark</item> </style> In: res/values/attrs.xml put the "attr" XML format reference In: res/menu/menu.xml files give the attr name <resources> <declare-styleable name="custom_menu"> <attr name="theme_dependent_icon_upload" format="reference"/> <attr name="theme_dependent_icon_share" format="reference"/> </declare-styleable> </resources> In order to display a theme you must set it before setcontentview(your_layout.xml) is called in your Activity. If you want your activity to restart, use recreate(); <item android:id="@+id/menu_item_share" android:orderincategory="100" android:showasaction="ifroom withtext" android:icon="?attr/theme_dependent_icon_share" android:title="@string/menu_item_share"/> if(lighttheme) settheme(r.style.customthemelight); else settheme(r.style.customthemedark);

10 Toolbar 1 The Toolbar is more configurable and a generalization of the ActionBar system Toolbar is a regular View included in a layout like any other View and thereby easier to position, animate and control Multiple distinct ToolBar elements can be defined within a single activity Using ToolBar as an ActionBar Add the v7 support library in the build.gradle (Module:app) file Disable the theme-provided ActionBar in res/values/styles.xml dependencies compile compile compile compile compile { filetree(include: ['*.jar'], dir: 'libs') 'com.android.support:support-v13:24.2.0' 'com.android.support:design:24.2.0' 'com.google.android.gms:play-services:9.4.0' 'com.android.support:appcompat-v7:24.2.0' <resources> <!-- Base application theme. --> <style name="apptheme" parent="theme.appcompat.light.noactionbar"> </style> </resources>

11 Toolbar 2 Add a Toolbar to your layout android:fitssystemwindows="true" ensures that the height of the activity is calculated correct <android.support.v7.widget.toolbar xmlns:android=" android:id="@+id/toolbar" /layout/toolbar.xml android:layout_height="wrap_content" Using the Toolbar in an activity xml layout android:layout_width="match_parent" android:fitssystemwindows="true" android:theme="@style/themeoverlay.appcompat.dark.actionbar" android:background="?attr/colorprimarydark"> </android.support.v7.widget.toolbar> <LinearLayout xmlns:android=" xmlns:app=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" /> <RelativeLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableintouchmode="true"> <TextView android:id="@+id/textstatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_centerhorizontal="true" android:text="status : Not connected" android:textsize="16sp" />...

12 Toolbar 3 Use the Toolbar layout... // when using the support library make sure that you import the following import android.support.v7.app.appcompatactivity; import android.support.v7.widget.toolbar; public class MyActivity extends AppCompatActivity { protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_my); // Find the toolbar view inside the activity layout Toolbar toolbar = (Toolbar) findviewbyid(r.id.toolbar); // Sets the Toolbar to act as the ActionBar for this Activity window. // Make sure the toolbar exists in the activity and is not null if (toolbar!= null) { setsupportactionbar(toolbar); // Menu icons are inflated just as they were with actionbar public boolean oncreateoptionsmenu(menu menu) { // Inflate the menu; this adds items to the toolbar if it is present. getmenuinflater().inflate(r.menu.menu_main, menu); return true; // Handle Menu selections as usual as well public boolean onoptionsitemselected(menuitem item) {...

13 Toolbar 4 (SettingsActivity fix) Material Settings and Toolbar with AS Settings Wizard /** * MaterialSettings: * no-actionbar-in-preferenceactivity-after-upgrade-to-support-library-v21/ # savedinstancestate */ protected void onpostcreate(bundle savedinstancestate) { super.onpostcreate(savedinstancestate); LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent(); Toolbar bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); root.addview(bar, 0); // insert at top // set correct Toolbar title if(mpreferenceheader!= null) { bar.settitle(mpreferenceheader); bar.setnavigationonclicklistener(new View.OnClickListener() { settings_toolbar.xml public void onclick(view v) { <?xml version="1.0" encoding="utf-8"?> finish(); <android.support.v7.widget.toolbar xmlns:android=" ); xmlns:app=" Full example in MapsProject android:id="@+id/toolbar" app:theme="@style/themeoverlay.appcompat.dark.actionbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:minheight="?attr/actionbarsize" app:navigationcontentdescription="@string/abc_action_bar_up_description" android:background="?attr/colorprimary" app:navigationicon="?attr/homeasupindicator" app:title="@string/action_settings" />

14 Themes and colors Customize the Color Palette If you select a specific Theme Customize the Status and App Bar In styles.xml and colors.xml <resources> <!-- inherit from the material theme --> <style name="apptheme" parent="android:theme.material"> <!-- Main theme colors --> <!-your app branding color for the app bar --> <item name="android:colorprimary">@color/primary</item> <!-darker variant for the status bar and contextual app bars --> <item name="android:colorprimarydark">@color/primary_dark</item> <!-theme UI controls like checkboxes and text fields --> <item name="android:coloraccent">@color/accent</item> <! > <item name="toolbarstyle">@style/widget.appcompat.toolbar</item> </style> </resources> <resources> <! > <color name="primary">#4caf50</color> <color name="primary_dark">#388e3c</color> <color name="accent">#8bc34a</color> </resources>

15 More advanced App Bars 1 Material Design: App Bar

16 More advanced App Bars 2 Implementing Effective Navigation Implement navigation patterns with tabs, swipe views, and navigation drawer you must master fragments before use!

17 Passing a Bundle What's the correct way to pass a bundle to the activity that is being launched from the current one? // You have a few options 1) Use the Bundle from the Intent Intent mintent = new Intent(this, Example.class); Bundle extras = mintent.getextras(); extras.putstring(key, value); 2) Create a new Bundle Intent mintent = new Intent(this, Example.class); Bundle mbundle = new Bundle(); mbundle.putstring(key, value); mintent.putextras(mbundle); 3) Use the putextra() shortcut method of the Intent Intent mintent = new Intent(this, Example.class); mintent.putextra(key, value); // Then, in the launched Activity, you would read them via String value = getintent().getextras().getstring(key); NOTE: Bundles have "get" and "put" methods for all the primitive types, advanced Parcelables, and Serializables. I just used Strings for demonstrational purposes.

18 Communication between Activities with explicit Intents 1 MainActivity (MainActivity example) not all code is present here public class MainActivity extends Activity implements View.OnClickListener { // we must implement onclick() since we implements View.OnClickListener interface in our class public void onclick(view view){ //create a new intent and explicit specify that it's target is SecondaryActivity... Intent intent = new Intent(this /*getapplicationcontext() or view.getcontext()*/, SecondaryActivity.class); //load the intent with a key "mykey" and assign it's value //to be whatever has been entered into the text field... intent.putextra("mykey", medittext1.gettext().tostring()); //launch the secondary activity and send the intent along with it //note that a request code is passed in as well so that when the //secondary activity returns control to this activity, //we can identify the source of the request... // startactivity(intent); // if we just want to start the other Activity with no return result startactivityforresult(intent, SECONDARY_ACTIVITY_REQUEST_CODE); // we need a handler for when the secondary activity finishes it's work and returns control // to this activity... we don't handle the resultcode Activity.RESULT_OK in this example protected void onactivityresult(int requestcode, int resultcode, Intent intent) { super.onactivityresult(requestcode, resultcode, intent); Bundle extras = intent.getextras(); medittext1.settext(extras!= null? extras.getstring("returnkey"):"nothing returned");

19 Communication between Activities with explicit Intents 2 SecondaryActivity - (MainActivity example) not all code is present here public void oncreate(bundle savedinstancestate) { if(savedinstancestate!= null)// if the activity is being resumed and instancestate have been saved mintentstring = savedinstancestate.getstring("mykey"); else { // check to see if a Bundle is present, the MainActivity may have called us Bundle extras = getintent().getextras(); // retrieves a map of extended data from the intent if(extras!= null){ mintentstring = extras.getstring("mykey");// get parameters from the Bundle out of the Intent else mintentstring = "nothing passed in"; // default init // set the textbox to display mintentstring medittext2.settext(mintentstring); public void onclick(view view){ mintentstring = medittext2.gettext().tostring(); //create a new intent... Intent intent = new Intent(); //add "returnkey" as a key and assign it the value //in the textbox... intent.putextra("returnkey", medittext2.gettext().tostring()); //get ready to send the result back to the caller (MainActivity) //and put our intent into it (RESULT_OK will tell the caller that //we have successfully accomplished our task.. setresult(activity.result_ok, intent); //close this Activity... finish(); Remember to create the SecondaryActivity in the AndroidManifest! <activity android:name= ".SecondaryActivity" <intent-filter> <action android:name= "android.intent.action.view"/> <category android:name= "android.intent.category.default"/> </intent-filter> </activity>

20 Shared Preferences 1 Storing and reading current preferences (data) in a simple Name (Key) Value pair format can be very handy in your application Saving application/ui settings and other properties to a limited Bundle Use with the proper lifecycle methods At next invokation/call the App can read the last used values easy If the App name is se.du.gpsmap" the shared preferences data is stored in a XML file under the /data/data/se.du.gpsmap/shared_prefs directory The datatypes: int, long, float, String and boolean are supported // Either MODE_PRIVATE, MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE SharedPreferences myprefs = getsharedpreferences("myprefs", Activity.MODE_PRIVATE); // SharedPreferences myprefs = PreferenceManager.getDefaultSharedPreferences(this); // store preference SharedPreferences.Editor prefseditor = myprefs.edit(); prefseditor.putstring("url_1", urltext.gettext().tostring()); // You have to commit otherwise the changes will not be remembered prefseditor.commit(); // at once, prefseditor.apply(); will do it in background // read preference String lastvalue_1 = myprefs.getstring(string key, String defaultvalue);

21 Shared Preferences 2 Data stored with onsaveinstancestate() will only be held in memory until the whole application is closed (no other activity is launched in front of it) Save in onpause() before the Activity is killable and restore in oncreate() public class SaveActivity extends Activity { public static final String MY_PREFS = "SaveActivityPrefs"; public static final String TEXT_INPUT = "text_input"; private EditText textinput; public void oncreate(bundle savedinstancestate) { textinput = (EditText) findviewbyid(r.id.text_input); if(savedinstancestate!= null) // if the activity is being resumed {... else{ // restore UI state from when last run of the application SharedPreferences settings = getsharedpreferences(my_prefs, MODE_PRIVATE); String currentinput = settings.getstring(text_input, ""); textinput.settext(currentinput); protected void onpause() { String currentinput = textinput.gettext().tostring(); // save UI state by getting a SharedPreferences editor SharedPreferences settings = getsharedpreferences(my_prefs, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putstring(text_input, currentinput); editor.commit(); // commit the edits super.onpause();

22 Shared Preferences Framework Android provides a standardized framework for setting preferences across all applications The framework uses categories and screens to group related settings PreferenceCategory is used to declare a set of preferences into one category PreferenceScreen presents a group of preferences in a new screen Possible elements to put preferences in are: CheckBox, EditText, List, MultiSelectList, Ringtone and Switch - Preference The Android system then generates a UI to manipulate the created preferences in the file: res/xml/preferences.xml These preferences are stored in shared preferences, which means they can be retrieved by using the getpreference() methods Resources which describe the preference framwork

23 Shared Preferences Framework Default settings etc. are stored in: res/xml/preferences.xml ListPreference store string arrays in: res/values/arrays.xml

24 Creating a Preference file Right click res/xml > New > XML Resource File Example content <PreferenceScreen xmlns:android=" > <PreferenceCategory android:title="@string/prefcat_general_title1" > <EditTextPreference android:defaultvalue="@string/pref_ueid_default" android:key="@string/pref_ueid" android:summary="@string/pref_ueid_summary" android:title="@string/pref_ueid_title" /> <ListPreference android:defaultvalue="@string/pref_low_speed_default" android:entries="@array/low_speed_names" android:entryvalues="@array/low_speed_values" android:key="@string/pref_low_speed" android:summary="@string/pref_low_speed_summary" android:title="@string/pref_low_speed_title" /> </PreferenceCategory> <PreferenceCategory android:title="@string/prefcat_general_title2"> <CheckBoxPreference android:key="@string/pref_admin_developer_mode" android:defaultvalue="@string/pref_admin_developer_mode_default" android:title="@string/pref_admin_developer_mode_title" android:summary="@string/pref_admin_developer_mode_summary" android:selectable="false"/> <EditTextPreference android:defaultvalue="@string/pref_http_server_url_default" android:key="@string/pref_http_server_url" android:summary="@string/pref_http_server_url_summary" android:title="@string/pref_http_server_url_title" android:dependency="@string/pref_admin_developer_mode"/> <CheckBoxPreference android:key="@string/pref_use_encryption" android:defaultvalue="@string/pref_use_encryption_default" android:title="@string/pref_use_encryption_title" android:summary="@string/pref_use_encryption_summary" android:dependency="@string/pref_admin_developer_mode"/> </PreferenceCategory> </PreferenceScreen>

25 Connecting a ListPreference Note that for the ListPreference, android:entries attribute are defined Example of res/values/arrays.xml and working with the preference XML file via UI <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="locale_names"> <item>automatic (default)</item> <item>english</item> <item>swedish</item> </string-array> <string-array name="locale_values"> <item></item> <item>en</item> <item>se</item> </string-array> <string-array name="video_resolution_names"> <item>480p (480x800), 2.5 Mbps, 30 fps (default)</item> <item>720p (720x1280), 5 Mbps, 30 fps</item> </string-array> <string-array name="video_resolution_values"> <item>480</item> <item>720</item> </string-array> </resources>

26 Shared Preferences Framework A settings/preference class which extends PreferenceActivity public class MyPreferences extends PreferenceActivity { private SharedPreferences myprefs; private OnSharedPreferenceChangeListener msplistener; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); Log.d(Consts.TAG, "MyPreferences oncreate executes..."); addpreferencesfromresource(r.xml.preferences); // gets a SharedPreferences instance that points to the default file // that is used by the preference framework in the given context myprefs = PreferenceManager.getDefaultSharedPreferences(this); // View all current preferences and values in logcat Map<String,?> localmap = myprefs.getall(); Log.d(Consts.TAG, localmap.tostring()); // Use instance field for listener // It will not be gc'd as long as this instance is kept referenced msplistener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onsharedpreferencechanged(sharedpreferences prefs, String key) { Log.d(Consts.TAG, "pref changed: " + key); ;

27 Using Preference Fragments Of course after API 11 settings are fragment based // Fragments provide a more flexible architecture for your application, compared // to using activities alone, no matter what kind of activity you're building public static class SettingsFragment extends PreferenceFragment { public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // Load the preferences from an XML resource addpreferencesfromresource(r.xml.preferences);... // you can then add this fragment to an Activity just // as you would for any other Fragment public class SettingsActivity extends Activity { protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // Display the fragment as the main content // Return the FragmentManager for interacting with // fragments associated with this activity getfragmentmanager() // Start a series of edit operations on the // Fragments associated with this FragmentManager.beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();

28 Use the AS Wizard - SettingsActivity May make things a bit advanced/complicated? Wizard adds fragment (two pane) adaptable code (prev. slide) Java SettingsActivity which extends from AppCompatPreferenceActivity XML pref_headers.xml which contains tablet setting headers and the corresponding underlying pref_data_sync.xml, pref_general.xml and pref_notification.xml // If you choose to use this settings framwork you must be able to extend/edit the XML and code a little bit. Specifically the note the methods: public Preference findpreference (CharSequence key) // Finds a Preference based on its key private static void bindpreferencesummarytovalue(preference preference) // Binds a preference's summary to its value // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design guidelines. bindpreferencesummarytovalue(findpreference("example_text")); bindpreferencesummarytovalue(findpreference("example_list")); Full example in MapsProject

29 Event Handlers 1 Most user interaction with an Android device is captured by the system and sent to a corresponding callback method For example, if the physical Back button is pressed, the onbackpressed() method is called Event listeners as View.OnClickListener() etc. are however the preferred method when available because they avoid the class extension overhead The system first sends any KeyEvent to the appropriate callback method in the in-focus activity or view Callbacks onkeyup(), onkeydown(), onkeylongpress() Physical key press callbacks ontrackballevent(), ontouchevent() Trackball and touchscreen press callbacks OnFocusChanged() Called when the view gains or loses focus

30 Event Handlers 2 Implement the "Press BACK again to exit" Toast user pattern User must click the phones back button again within two seconds private boolean doublebacktoexitpressedonce = false; /** Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want. */ public void onbackpressed() { if (doublebacktoexitpressedonce) { super.onbackpressed(); return; this.doublebacktoexitpressedonce = true; Utils.showToastMessage(this, "Press BACK again to exit"); // Causes the Runnable r to be added to the message queue, to be run after the specified amount // of time elapses. The runnable will be run on the thread to which this handler is attached. new Handler().postDelayed(new Runnable() { public void run() { doublebacktoexitpressedonce = false;, 2000);

31 Event Handlers 3 Physical buttons are most for programming games and other specific usages when events listners are not available or usable. The Power button, RECENTS and HOME key are intercepted by the system and do not reach the application. Some buttons as the BACK key should intercept onkeyup() because they might not be physical keys. public boolean onkeydown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_CAMERA) { return true; // consume event, hence do nothing on camera button // let event propagate in class tree return super.onkeydown(keycode, event); Example

32 Detect Touch and Gestures A "touch gesture" occurs when a user places one or more fingers on the touch screen, and your application interprets that pattern of touches as a particular gesture There are correspondingly two phases to gesture detection 1. Gathering data about touch events 2. Interpreting the data to see if it meets the criteria for any of the gestures your app supports Gather Data When a user places one or more fingers on the screen, this triggers the callback ontouchevent() on the View that received the touch events. For each sequence of touch events (position, pressure, size, addition of another finger, etc.) that is ultimately identified as a gesture, ontouchevent() is fired several times The gesture starts when the user first touches the screen, continues as the system tracks the position of the user's finger(s), and ends by capturing the final event of the user's fingers leaving the screen. Throughout this interaction, the MotionEvent delivered to ontouchevent() provides the details of every interaction. Your app can use the data provided by the MotionEvent to determine if a gesture it cares about happened

33 Detect Touch To intercept touch events in an Activity or View, override the ontouchevent() callback /** */ public boolean ontouchevent(motionevent event) { // get pointer index from the event object int pointerindex = event.getactionindex(); // get pointer ID int pointerid = event.getpointerid(pointerindex); // get masked (not specific to a pointer) action int action = event.getactionmasked(); switch(action) { case (MotionEvent.ACTION_DOWN) : Log.d(TAG,"Action was DOWN"); return true; case (MotionEvent.ACTION_MOVE) : Log.d(TAG, "Action was MOVE"); return true; case (MotionEvent.ACTION_UP) : Log.d(TAG,"Action was UP"); return true; case (MotionEvent.ACTION_CANCEL) : Log.d(TAG,"Action was CANCEL"); return true; case (MotionEvent.ACTION_OUTSIDE) : Log.d(TAG,"Movement occurred outside bounds " + "of current screen element"); return true; default : return super.ontouchevent(event); See the touch and gesture SwiperDiaper example project

34 Detect Gestures Android provides the GestureDetector class for detecting common gestures. Some of the gestures it supports include ondown(), onlongpress(), onfling() etc. You can use GestureDetector in conjunction with ontouchevent() public class MainActivity extends Activity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { private static final String TAG = MainActivity.class.getSimpleName(); private TextView textmessage; private GestureDetector mgesturedetector; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); // Instantiate the gesture detector with the application context and an implementation of GestureDetector.OnGestureListener mgesturedetector = new GestureDetector(this, this); // Set the gesture detector as the double tap listener. mgesturedetector.setondoubletaplistener(this); textmessage = (TextView)findViewById(R.id.textMessage); public boolean onscroll(motionevent motionevent, MotionEvent motionevent1, float v, float v1) { Log.d(TAG,"onScroll: " + motionevent.tostring()); textmessage.settext("onscroll"); return true; public boolean onfling(motionevent motionevent, MotionEvent motionevent1, float v, float v1) { Log.d(TAG,"onFling: " + motionevent.tostring()); textmessage.settext("onfling"); return true; public boolean ontouchevent(motionevent event) { // Analyzes the given motion event and if applicable triggers the appropriate callbacks on the GestureDetector.OnGestureListener supplied mgesturedetector.ontouchevent(event); // Be sure to call the superclass implementation return super.ontouchevent(event);...

35 Seekbar and Spinner <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10px" android:orientation="vertical"> <SeekBar android:layout_height="wrap_content" android:layout_marginbottom="15px" android:layout_width="fill_parent" /> <Spinner android:layout_margintop="15px" android:layout_height="wrap_content" android:layout_width="fill_parent" /> </LinearLayout> spinner_seekbar.xml spinner_entry.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android=" android:gravity="center" android:textcolor="#000" android:textsize="40sp" android:layout_width="fill_parent" android:layout_height="wrap_content"> </TextView>

36 Adapters 1 An Adapter represents a bridge between data (such as an array or list) and a View (such as a ListView or a Spinner) The Adapter creates the child views representing individual data The adapter automatically updates the view(s) if the underlying data is changed // create a list/array private static final String[] moceans = { "Pacific", "Atlantic", "Indian", "Arctic", "Southern" ; // bind the array to the spinner mfavoriteocean = (Spinner) findviewbyid(r.id.spinner); ArrayAdapter<String> madapter = new ArrayAdapter<String>(this, R.layout.spinner_entry); madapter.setdropdownviewresource(r.layout.spinner_entry); for(int idx=0; idx<moceans.length; idx++) madapter.add(moceans[idx]); mfavoriteocean.setadapter(madapter);

37 Adapters 2 The listener can access underlying data via the adapter A spinner does not support item click events. Calling this method will raise an exception. You must use OnItemSelectedListener() instead mfavoriteocean.setonitemselectedlistener(new OnItemSelectedListener() { public void onitemselected(adapterview<?> parent, View view, int position, long id) { showtoastmessage("spinner: " + parent.getitematposition(position).tostring()); public void onnothingselected(adapterview<?> parent) { showtoastmessage("spinner onnothingselected!"); );

38 Seekbar, Spinner and ArrayAdapter public class UITest extends Activity { private static final String[] moceans = { "Pacific", "Atlantic", "Indian", "Arctic", "Southern" ; private SeekBar mseekbar; private Spinner mfavoriteocean; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.spinner_seekbar); mfavoriteocean = (Spinner) findviewbyid(r.id.spinner); ArrayAdapter<String> madapter = new ArrayAdapter<String>(this, R.layout.spinner_entry); madapter.setdropdownviewresource(r.layout.spinner_entry); for(int idx=0; idx<moceans.length; idx++) madapter.add(moceans[idx]); mfavoriteocean.setadapter(madapter); mfavoriteocean.setonitemselectedlistener(new OnItemSelectedListener() { public void onitemselected(adapterview<?> parent, View view, int position, long id) { showtoastmessage("spinner: " + parent.getitematposition(position).tostring()); public void onnothingselected(adapterview<?> parent) { showtoastmessage("spinner onnothingselected!"); ); mseekbar = (SeekBar) findviewbyid(r.id.seekbar1); mseekbar.setprogress(50); mseekbar.setonseekbarchangelistener(new SeekBar.OnSeekBarChangeListener() { public void onprogresschanged(seekbar seekbar, int progress, boolean fromuser) { if(fromuser){ //showtoastmessage("seekbar: " + progress); mtv1.settext("seekbar: " + progress); public void onstarttrackingtouch(seekbar seekbar) { public void onstoptrackingtouch(seekbar seekbar) { ); private void showtoastmessage(string msg){ Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

39 Lab review - Android Lab2 List with topics you need to understand before next laboration You must be able or know how to Understand all the previous points from former labs Make a new app from scratch on your own with recepies (solutions) from other apps Manage View.OnClickListener touch events (anyone of the 4 button event methods) Create additional Activities in an app Manage SharedPreferences in a PreferenceActivity Understand and be able to use the lifecycle methods plus the onrestoreinstancestate and onsaveinstancestate methods Use UI things as OptionsMenu, ActionBar/Toolbar and AlertDialog etc.

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

Mobila applikationer och trådlösa nät, HI1033, HT2012 Mobila applikationer och trådlösa nät, HI1033, HT2012 Today: - User Interface basics - View components - Event driven applications and callbacks - Menu and Context Menu - ListView and Adapters - Android

More information

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

Mobila applikationer och trådlösa nät, HI1033, HT2013 Mobila applikationer och trådlösa nät, HI1033, HT2013 Today: - User Interface basics - View components - Event driven applications and callbacks - Menu and Context Menu - ListView and Adapters - Android

More information

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

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed. Action Bar Introduction The Action Bar is a widget that is shown on top of the screen. It includes the application logo on its left side together with items available from the options menu on the right.

More information

Meniu. Create a project:

Meniu. Create a project: 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.

More information

Mobile and Ubiquitous Computing: Android Programming (part 3)

Mobile and Ubiquitous Computing: Android Programming (part 3) Mobile and Ubiquitous Computing: Android Programming (part 3) Master studies, Winter 2015/2016 Dr Veljko Pejović Veljko.Pejovic@fri.uni-lj.si Based on Programming Handheld Systems, Adam Porter, University

More information

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

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Android Application Model I CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Rajiv Ramnath 1 Framework Support (e.g. Android) 2 Framework Capabilities

More information

Android Programs Day 5

Android Programs Day 5 Android Programs Day 5 //Android Program to demonstrate the working of Options Menu. 1. Create a New Project. 2. Write the necessary codes in the MainActivity.java to create OptionMenu. 3. Add the oncreateoptionsmenu()

More information

Android Application Model I

Android Application Model I Android Application Model I CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Rajiv Ramnath Reading: Big Nerd Ranch Guide, Chapters 3, 5 (Activities);

More information

05. RecyclerView and Styles

05. RecyclerView and Styles 05. RecyclerView and Styles 08.03.2018 1 Agenda Intents Creating Lists with RecyclerView Creating Cards with CardView Application Bar Menu Styles and Themes 2 Intents 3 What is Intent? An Intent is an

More information

Mobile Application Development MyRent Settings

Mobile Application Development MyRent Settings Mobile Application Development MyRent Settings Waterford Institute of Technology October 13, 2016 John Fitzgerald Waterford Institute of Technology, Mobile Application Development MyRent Settings 1/19

More information

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

Android Specifics. Jonathan Diehl (Informatik 10) Hendrik Thüs (Informatik 9) Android Specifics Jonathan Diehl (Informatik 10) Hendrik Thüs (Informatik 9) Android Specifics ArrayAdapter Preferences Widgets Jonathan Diehl, Hendrik Thüs 2 ArrayAdapter Jonathan Diehl, Hendrik Thüs

More information

Open Lecture Mobile Programming. Intro to Material Design

Open Lecture Mobile Programming. Intro to Material Design Open Lecture Mobile Programming Intro to Material Design Agenda Introduction to Material Design Applying a Material Theme Toolbar/Action Bar Navigation Drawer RecyclerView CardView Support Design Widgets/Tools

More information

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.

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. 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. 1) App Icon 3) Action Buttons 2)View Control 4) Action Overflows

More information

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State EMBEDDED SYSTEMS PROGRAMMING 2016-17 Application Tip: Saving State THE PROBLEM How to save the state (of a UI, for instance) so that it survives even when the application is closed/killed The state should

More information

Mobile Programming Lecture 7. Dialogs, Menus, and SharedPreferences

Mobile Programming Lecture 7. Dialogs, Menus, and SharedPreferences Mobile Programming Lecture 7 Dialogs, Menus, and SharedPreferences Agenda Dialogs Menus SharedPreferences Android Application Components 1. Activity 2. Broadcast Receiver 3. Content Provider 4. Service

More information

CS378 -Mobile Computing. More UI -Part 2

CS378 -Mobile Computing. More UI -Part 2 CS378 -Mobile Computing More UI -Part 2 Special Menus Two special application menus options menu context menu Options menu replaced by action bar (API 11) menu action bar 2 OptionsMenu User presses Menu

More information

Starting Another Activity Preferences

Starting Another Activity Preferences Starting Another Activity Preferences Android Application Development Training Xorsat Pvt. Ltd www.xorsat.net fb.com/xorsat.education Outline Starting Another Activity Respond to the Button Create the

More information

Android Navigation Drawer for Sliding Menu / Sidebar

Android Navigation Drawer for Sliding Menu / Sidebar Android Navigation Drawer for Sliding Menu / Sidebar by Kapil - Tuesday, December 15, 2015 http://www.androidtutorialpoint.com/material-design/android-navigation-drawer-for-sliding-menusidebar/ YouTube

More information

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

Multiple devices. Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers Multiple devices Multiple devices Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers Create a new directory in your project's res/ and name it using the

More information

MotionEvents Touch Handling Gestures

MotionEvents Touch Handling Gestures MotionEvents Touch Handling Gestures Represents a movement in an input device reading pen, trackball, mouse, finger Action Code State change that occurred Action Values Position and movement properties,

More information

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

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 4. Workshop Workshop 1. Create an Option Menu, and convert it into Action Bar (Page 1 8) Create an simple Option Menu Convert Option Menu into Action Bar Create Event Listener for Menu and Action Bar Add System Icon

More information

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

TextView. A label is called a TextView. TextViews are typically used to display a caption TextViews are not editable, therefore they take no input 1 UI Components 2 UI Components 3 A label is called a TextView. TextView TextViews are typically used to display a caption TextViews are not editable, therefore they take no input - - - - - - -

More information

Android Using Menus. Victor Matos Cleveland State University

Android Using Menus. Victor Matos Cleveland State University 8 Android Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright 2008-2009 CommonsWare, LLC. ISBN: 978-0-9816780-0-9 & Android Developers http://developer.android.com/index.html

More information

Android Using Menus. Victor Matos Cleveland State University

Android Using Menus. Victor Matos Cleveland State University Lesson 8 Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright 2008-2009 CommonsWare, LLC. ISBN: 978-0-9816780-0-9 & Android Developers http://developer.android.com/index.html

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu India Summer 2012 Review Session Android and Web Working with Views Working with Views Create a new Android project. The app name should

More information

Spring Lecture 5 Lecturer: Omid Jafarinezhad

Spring Lecture 5 Lecturer: Omid Jafarinezhad Mobile Programming Sharif University of Technology Spring 2016 - Lecture 5 Lecturer: Omid Jafarinezhad Storage Options Android provides several options for you to save persistent application data. The

More information

Our First Android Application

Our First Android Application Mobile Application Development Lecture 04 Imran Ihsan Our First Android Application Even though the HelloWorld program is trivial in introduces a wealth of new ideas the framework, activities, manifest,

More information

Software Engineering Large Practical: Storage, Settings and Layouts. Stephen Gilmore School of Informatics October 27, 2017

Software Engineering Large Practical: Storage, Settings and Layouts. Stephen Gilmore School of Informatics October 27, 2017 Software Engineering Large Practical: Storage, Settings and Layouts Stephen Gilmore School of Informatics October 27, 2017 Contents 1. Storing information 2. Settings 3. Layouts 1 Storing information Storage

More information

Mobile and Ubiquitous Computing: Android Programming (part 4)

Mobile and Ubiquitous Computing: Android Programming (part 4) Mobile and Ubiquitous Computing: Android Programming (part 4) Master studies, Winter 2015/2016 Dr Veljko Pejović Veljko.Pejovic@fri.uni-lj.si Examples from: Mobile and Ubiquitous Computing Jo Vermeulen,

More information

INTRODUCTION TO ANDROID

INTRODUCTION TO ANDROID INTRODUCTION TO ANDROID 1 Niv Voskoboynik Ben-Gurion University Electrical and Computer Engineering Advanced computer lab 2015 2 Contents Introduction Prior learning Download and install Thread Android

More information

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

Have a development environment in 256 or 255 Be familiar with the application lifecycle Upcoming Assignments Readings: Chapter 4 by today Horizontal Prototype due Friday, January 22 Quiz 2 today at 2:40pm Lab Quiz next Friday during lecture time (2:10-3pm) Have a development environment in

More information

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

Overview. What are layouts Creating and using layouts Common layouts and examples Layout parameters Types of views Event listeners Layouts and Views http://developer.android.com/guide/topics/ui/declaring-layout.html http://developer.android.com/reference/android/view/view.html Repo: https://github.com/karlmorris/viewsandlayouts Overview

More information

Introducing the Android Menu System

Introducing the Android Menu System Introducing the Android Menu System If you ve ever tried to navigate a mobile phone menu system using a stylus or trackball, you ll know that traditional menu systems are awkward to use on mobile devices.

More information

Embedded Systems Programming - PA8001

Embedded Systems Programming - PA8001 Embedded Systems Programming - PA8001 http://goo.gl/ydeczu Lecture 9 Mohammad Mousavi m.r.mousavi@hh.se Center for Research on Embedded Systems School of Information Science, Computer and Electrical Engineering

More information

Mobile Application Development Android

Mobile Application Development Android Mobile Application Development Android Lecture 2 MTAT.03.262 Satish Srirama satish.srirama@ut.ee Android Lecture 1 -recap What is Android How to develop Android applications Run & debug the applications

More information

Intents. Your first app assignment

Intents. Your first app assignment Intents Your first app assignment We will make this. Decidedly lackluster. Java Code Java Code XML XML Preview XML Java Code Java Code XML Buttons that work

More information

Vienos veiklos būsena. Theory

Vienos veiklos būsena. Theory Vienos veiklos būsena Theory While application is running, we create new Activities and close old ones, hide the application and open it again and so on, and Activity can process all these events. It is

More information

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml Android Application Written in Java (it s possible to write native code) Good

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi Introduction An application is composed of at least one Activity GUI It is a software component that stays behind a GUI (screen) Activity It runs inside the

More information

android-espresso #androidespresso

android-espresso #androidespresso android-espresso #androidespresso Table of Contents About 1 Chapter 1: Getting started with android-espresso 2 Remarks 2 Examples 2 Espresso setup instructions 2 Checking an Options Menu items (using Spoon

More information

Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento

Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento Let s work with the listener Button button = ; button.setonclicklistener(new.onclicklistener() { public void

More information

Adapter.

Adapter. 1 Adapter An Adapter object acts as a bridge between an AdapterView and the underlying data for that view The Adapter provides access to the data items The Adapter is also responsible for making a View

More information

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters Mobile Programming Lecture 5 Composite Views, Activities, Intents and Filters Lecture 4 Review How do you get the value of a string in the strings.xml file? What are the steps to populate a Spinner or

More information

UI Fragment.

UI Fragment. UI Fragment 1 Contents Fragments Overviews Lifecycle of Fragments Creating Fragments Fragment Manager and Transactions Adding Fragment to Activity Fragment-to-Fragment Communication Fragment SubClasses

More information

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering Getting Started Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador 1 Goals Setting up your development environment Android Framework

More information

EMBEDDED SYSTEMS PROGRAMMING UI and Android

EMBEDDED SYSTEMS PROGRAMMING UI and Android EMBEDDED SYSTEMS PROGRAMMING 2016-17 UI and Android STANDARD GESTURES (1/2) UI classes inheriting from View allow to set listeners that respond to basic gestures. Listeners are defined by suitable interfaces.

More information

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

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar Mobile Application Development Higher Diploma in Science in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology

More information

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

Create Parent Activity and pass its information to Child Activity using Intents. Create Parent Activity and pass its information to Child Activity using Intents. /* MainActivity.java */ package com.example.first; import android.os.bundle; import android.app.activity; import android.view.menu;

More information

Android Development Community. Let s do Material Design

Android Development Community. Let s do Material Design Let s do Material Design Agenda Introduction to Material Design Toolbar Navigation Drawer SwipeRefreshLayout RecyclerView Floating Action Button CardView Toolbar - Lives in package android.support.v7.widget

More information

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

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology Android App Development Mr. Michaud ICE Programs Georgia Institute of Technology Android Operating System Created by Android, Inc. Bought by Google in 2005. First Android Device released in 2008 Based

More information

Fragments. Lecture 11

Fragments. Lecture 11 Fragments Lecture 11 Situational layouts Your app can use different layouts in different situations Different device type (tablet vs. phone vs. watch) Different screen size Different orientation (portrait

More information

Arrays of Buttons. Inside Android

Arrays of Buttons. Inside Android Arrays of Buttons Inside Android The Complete Code Listing. Be careful about cutting and pasting.

More information

Mobile Programming Lecture 3. Resources, Selection, Activities, Intents

Mobile Programming Lecture 3. Resources, Selection, Activities, Intents Mobile Programming Lecture 3 Resources, Selection, Activities, Intents Lecture 2 Review What widget would you use to allow the user to enter a yes/no value a range of values from 1 to 100 What's the benefit

More information

1. Simple List. 1.1 Simple List using simple_list_item_1

1. Simple List. 1.1 Simple List using simple_list_item_1 1. Simple List 1.1 Simple List using simple_list_item_1 1. Create the Android application with the following attributes. Application Name: MySimpleList Project Name: Package Name: MySimpleList com.example.mysimplelist

More information

Building User Interface for Android Mobile Applications II

Building User Interface for Android Mobile Applications II Building User Interface for Android Mobile Applications II Mobile App Development 1 MVC 2 MVC 1 MVC 2 MVC Android redraw View invalidate Controller tap, key pressed update Model MVC MVC in Android View

More information

Preferences. Marco Ronchetti Università degli Studi di Trento

Preferences. Marco Ronchetti Università degli Studi di Trento 1 Preferences Marco Ronchetti Università degli Studi di Trento SharedPreferences SharedPreferences allows to save and retrieve persistent key-value pairs of primitive data types. This data will persist

More information

Hello World. Lesson 1. Android Developer Fundamentals. Android Developer Fundamentals. Layouts, and. NonCommercial

Hello World. Lesson 1. Android Developer Fundamentals. Android Developer Fundamentals. Layouts, and. NonCommercial Hello World Lesson 1 This work is licensed This under work a Creative is is licensed Commons under a a Attribution-NonCommercial Creative 4.0 Commons International Attribution- License 1 NonCommercial

More information

getcount getitem getitemid getview com.taxi Class MainActivity drawerlayout drawerleft drawerright...

getcount getitem getitemid getview com.taxi Class MainActivity drawerlayout drawerleft drawerright... Contents com.taxi.ui Class CallDialog... 3 CallDialog... 4 show... 4 build... 5 com.taxi.custom Class CustomActivity... 5 TOUCH... 6 CustomActivity... 6 onoptionsitemselected... 6 onclick... 6 com.taxi.model

More information

Understanding Application

Understanding Application Introduction to Android Application Development, Android Essentials, Fifth Edition Chapter 4 Understanding Application Components Chapter 4 Overview Master important terminology Learn what the application

More information

Computer Science Large Practical: Storage, Settings and Layouts. Stephen Gilmore School of Informatics October 26, 2017

Computer Science Large Practical: Storage, Settings and Layouts. Stephen Gilmore School of Informatics October 26, 2017 Computer Science Large Practical: Storage, Settings and Layouts Stephen Gilmore School of Informatics October 26, 2017 Contents 1. Storing information 2. Kotlin compilation 3. Settings 4. Layouts 1 Storing

More information

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license Android Android Mobile operating system developed by Google A complete stack OS, framework A rich set of applications Email, calendar, browser, maps, text messaging, contacts, camera, dialer, music player,

More information

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs Overview MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs Lecture: MVC Model View Controller What is an App? Android Activity Lifecycle Android Debugging Fixing Rotations & Landscape Layouts Localization

More information

Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department. Mobile Computing ECOM Eng. Wafaa Audah.

Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department. Mobile Computing ECOM Eng. Wafaa Audah. Islamic University of Gaza Faculty of Engineering Computer Engineering Department Mobile Computing ECOM 5341 By Eng. Wafaa Audah July 2013 1 Launch activitits, implicit intents, data passing & start activity

More information

Android Basics. Android UI Architecture. Android UI 1

Android Basics. Android UI Architecture. Android UI 1 Android Basics Android UI Architecture Android UI 1 Android Design Constraints Limited resources like memory, processing, battery à Android stops your app when not in use Primarily touch interaction à

More information

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

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator. Simple Android Application for Native Calculator Aim: To develop a Simple Android Application for Native Calculator. Procedure: Creating a New project: Open Android Stdio and then click on File -> New

More information

When programming in groups of people, it s essential to version the code. One of the most popular versioning tools is git. Some benefits of git are:

When programming in groups of people, it s essential to version the code. One of the most popular versioning tools is git. Some benefits of git are: ETSN05, Fall 2017, Version 1.0 Software Development of Large Systems Lab 2 preparations Read through this document carefully. In order to pass lab 2, you will need to understand the topics presented in

More information

CS371m - Mobile Computing. More UI Navigation, Fragments, and App / Action Bars

CS371m - Mobile Computing. More UI Navigation, Fragments, and App / Action Bars CS371m - Mobile Computing More UI Navigation, Fragments, and App / Action Bars EFFECTIVE ANDROID NAVIGATION 2 Clicker Question Have you heard of the terms Back and Up in the context of Android Navigation?

More information

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

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings. Hello World Lab Objectives: Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.xml What to Turn in: The lab evaluation

More information

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

ActionBar. import android.support.v7.app.actionbaractivity; public class MyAppBarActivity extends ActionBarActivity { } Android ActionBar import android.support.v7.app.actionbaractivity; public class MyAppBarActivity extends ActionBarActivity { Layout, activity.xml

More information

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Activity Basics Manifest File AndroidManifest.xml Central configuration of Android application Defines: Name of application Icon for

More information

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

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar Mobile Application Development Higher Diploma in Science in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology

More information

GUI Widget. Lecture6

GUI Widget. Lecture6 GUI Widget Lecture6 AnalogClock/Digital Clock Button CheckBox DatePicker EditText Gallery ImageView/Button MapView ProgressBar RadioButton Spinner TextView TimePicker WebView Android Widgets Designing

More information

Distributed Systems Assignment 1

Distributed Systems Assignment 1 Distributed Systems Assignment 1 Marian.george@inf.ethz.ch Distributed Systems Assignment 1 1 The Exercise Objectives Get familiar with Android programming Emulator, debugging, deployment Learn to use

More information

Lecture 7: Data Persistence : shared preferences. Lecturer : Ali Kadhim Al-Bermani Mobile Fundamentals and Programming

Lecture 7: Data Persistence : shared preferences. Lecturer : Ali Kadhim Al-Bermani Mobile Fundamentals and Programming University of Babylon College of Information Technology Department of Information Networks Mobile Fundamentals and Programming Lecture 7: Data Persistence : shared preferences Lecturer : Ali Kadhim Al-Bermani

More information

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

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept. MAD ASSIGNMENT NO 2 Submitted by: Rehan Asghar BSSE 7 15126 AUGUST 25, 2017 SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept. Android Widgets There are given a lot of android widgets with simplified

More information

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

Interface ใน View class ประกอบด วย Boonrit kidngan Interface ใน View class ประกอบด วย View.OnClickListener เม อม การ click View.OnLongClickListener เม อม การ click ค าง View.OnFocusChangeListener เม อเปล ยนการเล อก View.OnKeyListener เม

More information

Saving application preferences

Saving application preferences Saving application preferences Adaptation of materials: dr Tomasz Xięski. Based on presentations made available by Victor Matos, Cleveland State University. Portions of this page are reproduced from work

More information

CMSC436: Fall 2013 Week 3 Lab

CMSC436: Fall 2013 Week 3 Lab CMSC436: Fall 2013 Week 3 Lab Objectives: Familiarize yourself with the Activity class, the Activity lifecycle, and the Android reconfiguration process. Create and monitor a simple application to observe

More information

CS 193A. Activity state and preferences

CS 193A. Activity state and preferences CS 193A Activity state and preferences This document is copyright (C) Marty Stepp and Stanford Computer Science. Licensed under Creative Commons Attribution 2.5 License. All rights reserved. Activity instance

More information

Android Data Storage

Android Data Storage Lesson 14 Android Persistency: Victor Matos Cleveland State University Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright 2008-2009 CommonsWare, LLC. ISBN: 978-0-9816780-0-9

More information

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment FRAGMENTS Fragments An activity is a container for views When you have a larger screen device than a phone like a tablet it can look too simple to use phone interface here. Fragments Mini-activities, each

More information

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation EMBEDDED SYSTEMS PROGRAMMING 2016-17 Application Tip: Managing Screen Orientation ORIENTATIONS Portrait Landscape Reverse portrait Reverse landscape ON REVERSE PORTRAIT Android: all four orientations are

More information

Screen Slides. The Android Studio wizard adds a TextView to the fragment1.xml layout file and the necessary code to Fragment1.java.

Screen Slides. The Android Studio wizard adds a TextView to the fragment1.xml layout file and the necessary code to Fragment1.java. Screen Slides References https://developer.android.com/training/animation/screen-slide.html https://developer.android.com/guide/components/fragments.html Overview A fragment can be defined by a class and

More information

Solving an Android Threading Problem

Solving an Android Threading Problem Home Java News Brief Archive OCI Educational Services Solving an Android Threading Problem Introduction by Eric M. Burke, Principal Software Engineer Object Computing, Inc. (OCI) By now, you probably know

More information

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

android:orientation=horizontal android:layout_margintop=30dp> <Button android:text=button2 Parametrų keitimas veikiančioje aplikacijoje Let s create a project: Project name: P0181_DynamicLayout3 Build Target: Android 2.3.3 Application name: DynamicLayout3 Package name: ru.startandroid.develop.dynamiclayout3

More information

CS371m - Mobile Computing. More UI Action Bar, Navigation, and Fragments

CS371m - Mobile Computing. More UI Action Bar, Navigation, and Fragments CS371m - Mobile Computing More UI Action Bar, Navigation, and Fragments ACTION BAR 2 Options Menu and Action Bar prior to Android 3.0 / API level 11 Android devices required a dedicated menu button Pressing

More information

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

UI, Continued. CS 2046 Mobile Application Development Fall Jeff Davidson CS 2046 UI, Continued CS 2046 Mobile Application Development Fall 2010 Announcements Office hours have started HW1 is out, due Monday, 11/1, at 11:59 pm Clarifications on HW1: To move where the text appears in

More information

ListView Containers. Resources. Creating a ListView

ListView Containers. Resources. Creating a ListView ListView Containers Resources https://developer.android.com/guide/topics/ui/layout/listview.html https://developer.android.com/reference/android/widget/listview.html Creating a ListView A ListView is a

More information

EMBEDDED SYSTEMS PROGRAMMING Android Services

EMBEDDED SYSTEMS PROGRAMMING Android Services EMBEDDED SYSTEMS PROGRAMMING 2016-17 Android Services APP COMPONENTS Activity: a single screen with a user interface Broadcast receiver: responds to system-wide broadcast events. No user interface Service:

More information

Lampiran Program : Res - Layout Activity_main.xml

More information

Android HelloWorld - Example. Tushar B. Kute,

Android HelloWorld - Example. Tushar B. Kute, Android HelloWorld - Example Tushar B. Kute, http://tusharkute.com Anatomy of Android Application Anatomy of Android Application Java This contains the.java source files for your project. By default, it

More information

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs EMBEDDED SYSTEMS PROGRAMMING 2015-16 Application Tip: Switching UIs THE PROBLEM How to switch from one UI to another Each UI is associated with a distinct class that controls it Solution shown: two UIs,

More information

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

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015 CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015 Comment and Evaluation: This lab introduces us about Android SDK and how to write a program for Android platform. The calculator is pretty easy, everything

More information

Topics of Discussion

Topics of Discussion Reference CPET 565 Mobile Computing Systems CPET/ITC 499 Mobile Computing Fragments, ActionBar and Menus Part 3 of 5 Android Programming Concepts, by Trish Cornez and Richard Cornez, pubslihed by Jones

More information

10.1 Introduction. Higher Level Processing. Word Recogniton Model. Text Output. Voice Signals. Spoken Words. Syntax, Semantics, Pragmatics

10.1 Introduction. Higher Level Processing. Word Recogniton Model. Text Output. Voice Signals. Spoken Words. Syntax, Semantics, Pragmatics Chapter 10 Speech Recognition 10.1 Introduction Speech recognition (SR) by machine, which translates spoken words into text has been a goal of research for more than six decades. It is also known as automatic

More information

CS 4330/5390: Mobile Application Development Exam 1

CS 4330/5390: Mobile Application Development Exam 1 1 Spring 2017 (Thursday, March 9) Name: CS 4330/5390: Mobile Application Development Exam 1 This test has 8 questions and pages numbered 1 through 7. Reminders This test is closed-notes and closed-book.

More information

Produced by. Mobile Application Development. Eamonn de Leastar

Produced by. Mobile Application Development. Eamonn de Leastar Mobile Application Development Produced by Eamonn de Leastar (edeleastar@wit.ie) Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie A First

More information

Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time

Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time The 1 activity 1 thing the user can do heuristic may not make sense for larger devices Application

More information

Data Persistence. Chapter 10

Data Persistence. Chapter 10 Chapter 10 Data Persistence When applications create or capture data from user inputs, those data will only be available during the lifetime of the application. You only have access to that data as long

More information

Mobile Computing Fragments

Mobile Computing Fragments Fragments APM@FEUP 1 Fragments (1) Activities are used to define a full screen interface and its functionality That s right for small screen devices (smartphones) In bigger devices we can have more interface

More information