CC7173 – WK5 (31/10/17)

Android fragments and intents

  1. Contents summary
    1. Concepts of Android Fragments and Intent
    2. Learn how to use the Fragments and Intent in Android app development
  2. Contents detailed
    1. Concepts of Android Fragments and Intent
      1. Fragments
        1. piece of an activity (sub-activity) which enable more modular activity design;
          1. possible to work with same result by activity, but fragments will be more modular, such as split screen / contents in fragments at small screens;
        2. Important points about fragment:
          1. contains own layout and its own behaviour with its own life cycle callbacks;
          2. add or remove fragments in an activity while the activity is running;
          3. can combine multiple fragments in a single activity to build a multi-plane UI;
          4. A fragment can be used in multiple activities;
          5. Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped;
          6. A fragment can implement a behaviour that has no user interface component;
          7. Fragments were added to the Android API in Honeycomb version of Android which API version 11;
        3. How to create a fragment
          1. by extending Fragment class;
          2. can insert a fragment into your activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element;
        4. Methods which can be overridden in fragment class
          1. onAttach()
            1. fragment instance is associated with an activity instance; fragment and the activity is not fully initialized;
            2. Typically you get in this method a reference to the activity which uses the fragment for further initialization work;
          2. onCreate()
            1. calls this method when creating the fragment;
            2. should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed;
          3. onCreateView()
            1. calls this callback when it’s time for the fragment to draw its user interface for the first time;
            2. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout;
            3. return null if the fragment does not provide a UI;
          4. onActivityCreated()
            1. is called after the onCreateView() method when the host activity is created;
            2. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object
          5. onStart()
            1. is called once the fragment gets visible;
          6. onResume()
            1. Fragment becomes active;
          7. onPause()
            1. system calls this method as the first indication that the user is leaving the fragment;
            2. usually where you should commit any changes that should be persisted beyond the current user session;
          8. onStop()
            1. Fragment going to be stopped by calling onStop();
          9. onDestroyView()
            1. Fragment view will destroy after call this method;
          10. onDestroy()
            1. to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform;
        5. How to use Fragments?
          1. Decide how many fragments you want to use in an activity; for example, to use two fragments to handle landscape and portrait modes of the device;
          2. based on number of fragments, create classes which will extend the Fragment class; The Fragment class has above mentioned callback functions;
          3. Corresponding to each fragment, you will need to create layout files in XML file. These files will have layout for the defined fragments;
          4. Finally modify activity file to define the actual logic of replacing fragments based on your requirement;
        6. Sample codes of (2 fragments) pressing two buttons to change colors in background;
      2. Intent (message)
        1. What is Android Intent?
          1. an abstract description of an operation to be performed;
          2. can be used with startActivity to launch an Activity,
          3. broadcastIntent to send it to any interested BroadcastReceiver components,
          4. startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service;
        2. How to use intent
          1. an Activity that needs to launch an email client and sends an email using your Android device
          2. Activity would send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver;
          3. The specified chooser gives the proper interface for the user to pick how to send your email data (Sample 1):Intent email = new Intent(Intent.ACTION_SEND, Uri.parse(“mailto:”)); email.putExtra(Intent.EXTRA_EMAIL, recipients); email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString()); email.putExtra(Intent.EXTRA_TEXT, body.getText().toString()); startActivity(Intent.createChooser(email, “Choose an email client from…”));
          4. Sample 2 – have an Activity that needs to open URL in a web browser on your Android device
            1. your Activity will send ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the web browser
            2. The Intent Resolver parses through a list of Activities and chooses the one that would best match your Intent, in this case, the Web Browser Activity;
            3. The Intent Resolver then passes your web page to the web browser and starts the Web Browser Activity
          5. Sample 3 – search as Londonmet on android search engine and it gives the result of londonmet in your an activity
        3. Deliver intents to different components:
          1. activities – Context.startActivity()
          2. services – Context.startService()
          3. broadcast receivers – Context.sendBroadcast()
        4. Intent components
          1. Intent” object as a message containing a bundle of information
            1. Information of interests for the receiver (e.g. data);
            2. Information of interests for the Android system (e.g. category);
          2. Component Name (i.e. the receiver)
            1. void setComponent(), or
            2. optional, i.e. implicit intent
          3. Action
            1. void setAction()
            2. A string naming the action to be performed;
            3. Pre-defined, or can be specified by the programmer;
              1. ACTION_CALL: Initiate a phone call
              2. ACTION_EDIT: Display data to edit
              3. ACTION_MAIN: Start as a main entry point, does not expect to receive data;
              4. ACTION_PICK: Pick an item from the data, return what was selected;
              5. ACTION_VIEW: Display the data to the user;
              6. ACTION_SEARCH: Performs a search
              7. Defined by programmer: it.example.projectpackage.FILL_DATA (package prefix + name action)
          4. Data
            1. void setData()
            2. Data passed from the caller to the called Component;
            3. Each data is specified by a name and/or type:
              1. Location of the data (URI) and Type of the data (MIME type);
              2. name: Uniform Resource Identifier (URI);
                1. scheme://host:port/path
                2. content://com.example.project:200/folder
                3. content://contacts/people
                4. content://contacts/people/1
              3. type: MIME (Multipurpose Internet Mail Extensions)-type
                1. Composed by two parts: a type and a subtype
                2. eg. Image/gif  image/jpeg; image/png; video/mp4; video/mpeg4; video/quicktime; video/ogg; application/;
          5. Category
            1. void addCategory()
            2. A string containing information about the kind of component that should handle the Intent;
            3. > 1 can be specified for an Intent
            4. Categories:
              1. CATEGORY_HOME: The activity displays the HOME screen;
              2. CATEGORY_LAUNCHER: The activity is listed in the top-level application launcher, and can be displayed;
              3. CATEGORY_PREFERENCE: The activity is a preference panel;
              4. CATEGORY_BROWSABLE: The activity can be invoked by the browser to display data referenced by a link.
          6. Extra
            1. void putExtras() getExtras()
            2. Additional information that should be delivered to the handler(e.g. parameters)
          7. Flags
            1. Additional information that instructs Android how to launch an activity, and how to treat it after executed;
        5. Intent types
          1. Explicit: target receiver is specified through the Component NameUsed to launch specific Activities;
            1. connected internal world of application, suppose if you wants to connect one activity to another activity, we can do this quote by explicit intent;
            2. typically used for application-internal messages – such as an activity starting a subordinate service or launching a sister activity
            3. // Explicit Intent by specifying its class nameIntent i = new Intent(FirstActivity.this, SecondActivity.class);// Starts TargetActivity startActivity(i);
          2. Implicit: The target receiver is specified by data type/names; The system chooses the receiver that matches the request;
            1. not name a target and the field for the component name is left blank;
            2. used to activate components in other applications;
              1. //Implicit Intent,
              2. Intent read1=new Intent();read1.setAction(android.content.Intent.ACTION_VIEW);read1.setData(ContactsContract.Contacts.CONTENT_URI);


            3. target component which receives the intent can use the getExtras() method to get the extra data sent by the source component;
    2. Learn how to use the Fragments and Intent in Android app development
  3. Lab5
  4. References
    1. Videos – Android tutorial for beginners – 77 – Fragment example.
    2. Videos – Android Intent Basic Example.
    3. Change default layout from ConstraintLayout to LinearLayout after AS 2.3.
      1. backup C:\Program Files\Android\Android Studio\plugins\android\lib\templates\activities\common\root\res\layout\simple.xml.ftl
      2. open simple.xml.ftl in editor (or simply Wordpad), then, replace contents below to simple.xml.ftl (may need to modify file permission in order to write and save):
        1. <?xml version=“1.0” encoding=“utf-8”?>
        2. <LinearLayout
        3.     xmlns:android=;
        4.     xmlns:app=;
        5.     android:layout_width=“match_parent”
        6.     android:layout_height=“match_parent”>
        7.     <TextView
        8.         android:layout_width=“wrap_content”
        9.         android:layout_height=“wrap_content”
        10.         android:text=“Hello World!”
        11.     />
        12. </LinearLayout>
      3. Then, new project will start with LinearLayout again;
  5. Follow-ups
    1. Research ConstraintLayout and parameters;
    2. Coding, coding and coding: 2 hours everyday…
    3. good habit to pre-lecture, but better read books and practice coding;


L5 - Fragments and Intents

CC7173 – WK5 (31/10/17)

CC7173 – WK4 (24/10/2017)

UI and Event handling

  1. Contents Summary
    1. GUI concept in Android
    2. Interfaces
    3. Layout options
    4. Android Event Management
  2. Contents detailed
    1. GUI concept in Android
      1. hierarchy of View and View group objects
        1. View: UI components such as button, textfields, imageviews
        2. ViewGroup: containers that have a layout defined controlling how View widget
          1. Controls location of Views in that ViewGroup
            1. LinearLayout: all children aligned in single direction, horizontally or vertically
            2. RelativeLayout: Child object relative to each other
            3. ListView: a list of scrollable items
            4. GridView: displays items in two-dimensional, scrollable grid
    2. Interfaces
      1. two ways you can create the interface(s) of your Application
        1. Code = write code using SDK with classes like LinearLayout, TextView, …
        2. XML = create XML files in res/Layout (i.e. main.xml) that contain Android XML view tags like <LinearLayout> <TextView>, etc
        3. XML would be better as it means a decoupling of design from Java code;
    3. Layout options
      1. Layouts defined with XML located in res/layout
        1. <TextView xmlns:android=”;

          1. xmlns:android  XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute;
          2. android:layout_width This attribute defines how much of the available width on the screen this View should consume. As it’s the only View so you want it to take up the entire screen, which is what a value of “fill_parent” means;
          3. android:layout_height This is just like android:layout_width, except that it refers to available screen height;
          4. android:text This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file;
        2. Visual creation of XML file
          1. Create File-> New->XML -> Layout XML File
          2. name xml file and layout type
          3. Drag and Drop widgets-> Call alter properties
            1. example of a login page with textView_TopLabel, textView_login, editText_Login, textView_password, editText_Password, button_Enter;
        3. LinearLayout
          1. arranges its children in a single column or a single row;
          2. setOrientation(): set direction of the row can be set; default is horizontal;
          3. setGravity(): specifies the alignment of all the child elements;
          4. LinearLayout.LayoutParams: specify that specific children grow to fill up any remaining space in the layout by setting the weight member of
        4. RelativeLayout
          1. Benefits:
            1. Can give more complex interface
            2. Know what will look like on different sized devices
            3. Position relative to another position
          2. Drawback
            1. to be flat –meaning you don’t want/need to nest RelativeLayouts in each other –sometimes may impact speed in rendering
          3. Parameters in XML or map to method calls in Java RelativeLayout class
            1. Position relative to Parent
              1. android:layout_alignParentTop
              2. android:layout_alignParentBottom
              3. android:layout_alignParentLeft
              4. android:layout_alignParentRight
                1. VALUE = ‘true’ —If “true”, moves to that edge of Parent
              5. android:layout_centerVertical
                1. VALUE= “true” — If “true”, centers this child vertically within its parent.
            2. Position relative to another widget
              1. android:layout_below,
              2. android:layout_above,
              3. android:layout_toLeftOf,
              4. android:layout_toRightOf
                1. VALUE=“resource ID of other widget” — Positions the top edge of this view below/aboveof  the view specified with a resource ID;
                2. OR Positions the left edge of this view to the left/right of the view specified with a resource ID;
        5. GridLayout
          1. GridView, such as buttons in calculator
    4. Android Event Management
      1. Event listeners
        1. interface in the View class that contains a single callback method;
        2. to be called when the View is triggered by user interaction with the item in the UI;
      2. Event Listeners Registration
        1. process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event;
      3. Event Handlers
        1. an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event;
      4. Views that have events (android.widget), such as
        1. Button
        2. CheckBox
        3. DatePicker
        4. EditText
        5. ImageView
        6. SearchView
        7. Spinner
      5. Event Handling (
        1. STEP 1: Decide what Widgets who’s events to process
        2. STEP 2: Define an event listener
        3. STEP 3: Register event listener with the View
          1. View.OnClickListener (for handling “clicks” on a View), View.OnTouchListener (for handling touch screen events in a View), and View.OnKeyListener (for handling device key presses within a View)
        4. Sample of adding a button to a program-based interface
          1. Button specified in XML layout we want to process/handle
          2. Implement Event Handler
            1. TWO OPTIONS – separate class to handle event(s), OR have the Activity containing the button do the event handling
          3. Register Event Handler
            1. public class ExampleActivity extends Activity implements OnClickListener {
              protected void onCreate(Bundle savedValues) {
              …        Button button = (Button)findViewById(;   //STEP 1
              button.setOnClickListener(this);   //STEP 3 – registration
              // Implement the OnClickListener callback      //STEP 2 –event handler
              public void onClick(View v) {
              // do something when the button is clicked

            2. often you may do an anonymous inner class instead or a regular class if you want to reuse it
        5. Handling events by having Main Activity implement Listener Interface (Why slide 25 & slide 31 are the same??)
          1. Goal
            1. Change color of a TextView when Button or RadioButton is pressed. Different colors depending on which pressed
          2. Approach
            1. Use an external class that implements View.OnClickListener
            2. Import android.view.View.OnClickListener, then say “implements OnClickListener
          3. Advantages
            1. can pass arguments to change behavior
            2. Separate classes generally promote loose coupling
            3. if event handler can be applied to different controls, it can be change independently from rest of app;
            4. in most real situations, behavior is tightly coupled to app anyhow;
          4. Disadvantages
            1. if you want to call code in main Activity, you need reference
            2. Even then, that code in main Activity must be public
    5. XML Interface Creation: doing XML would be better as it means a decoupling of design from Java code;
    6. XML tags and explanation
    7. Event handling
      1. 3 steps
      2. Program of randomly change color
      3. Class
        1. Separate Listener Class
          1. public class ColorSetter Implements OnClickListener (
        2. Named Inner Class
          1. private class ColorSetter Implements OnClickListener (
  3. References
    1. Videos – Android Hands On Training Series – Exercise 1: Android UI Components, Activity, Fonts & Colors.
    2. Videos – Android development tutorial 3 – layout and buttons.
    3. Videos – Click events and Button onClick- Android Studio tutorial.
    4. Videos – Android Studio Tutorial – 08 – Respond to Button Click Events.
    5. Videos – Sketch UI Design to Android Studio XML Tutorial.
  4. Follow-ups
    1. proposal framework
      1. Practise Weekly Exercises
      2. Customize weekly exercises
      3. Try other web / book exercises
    2. read lot of materials
    3. widget
    4. Prepare programs, youtube, questions before class
    5. familiar with components within codes
      1. declaration
      2. definition
      3. registration
      4. functions / class calling
    6. What is the difference between inner class and public class?
      1. Compare the code in Excel
CC7173 – WK4 (24/10/2017)