UI Fragment.

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

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

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

Mobile Computing Fragments

Programming with Android: Android for Tablets. Dipartimento di Scienze dell Informazione Università di Bologna

Fragments. Fragments may only be used as part of an ac5vity and cannot be instan5ated as standalone applica5on elements.

Fragments and the Maps API

Activities and Fragments

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

Building User Interface for Android Mobile Applications II

Fragments. Lecture 11

Mobile Development Lecture 10: Fragments

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

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

Programmatically Working with Android Fragments

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

Android Basics. Android UI Architecture. Android UI 1

States of Activities. Active Pause Stop Inactive

Fragments. Lecture 10

WebView Fragments Navigation Drawer

EMBEDDED SYSTEMS PROGRAMMING UI and Android

CS 4518 Mobile and Ubiquitous Computing Lecture 5: Rotating Device, Saving Data, Intents and Fragments Emmanuel Agu

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

Overview of Activities

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Minds-on: Android. Session 2

FRAGMENTS.

UNDERSTANDING ACTIVITIES

LECTURE NOTES OF APPLICATION ACTIVITIES

User Interface Development. CSE 5236: Mobile Application Development Instructor: Adam C. Champion Course Coordinator: Dr.

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

CS 4330/5390: Mobile Application Development Exam 1

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING

EMBEDDED SYSTEMS PROGRAMMING Application Basics

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

CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu

Activities. Repo:

Android Fundamentals - Part 1

Spring Lecture 5 Lecturer: Omid Jafarinezhad

ANDROID USER INTERFACE

You ve been told lies about Fragments.

CHAPTER 4. Fragments ActionBar Menus

Android Application Development

Vienos veiklos būsena. Theory

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

University of Babylon - College of IT SW Dep. - Android Assist. Lect. Wadhah R. Baiee Activities

Lifecycle-Aware Components Live Data ViewModel Room Library

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

Fragment Example Create the following files and test the application on emulator or device.

Lab 1: Getting Started With Android Programming

Android Activities. Akhilesh Tyagi

Android Programming: More User Interface. CS 3: Computer Programming in Java

CS 528 Mobile and Ubiquitous Computing Lecture 3: Android UI, WebView, Android Activity Lifecycle Emmanuel Agu

Repairing crashes in Android Apps. Shin Hwei Tan Zhen Dong Xiang Gao Abhik Roychoudhury National University of Singapore

CS 528 Mobile and Ubiquitous Computing Lecture 4a: Fragments, Camera Emmanuel Agu

Fragments may only be used as part of an activity and cannot be instantiated as standalone application elements.

CE881: Mobile & Social Application Programming

Lifecycle Callbacks and Intents

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

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle

Understanding Application

More Effective Layouts

Upon completion of the second part of the lab the students will have:

ListView Containers. Resources. Creating a ListView

Instant Android Fragmentation Management How-to

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

Answers to Exercises

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

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

Mobile Application Development Android

Our First Android Application

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

Introduction to Android

05. RecyclerView and Styles

Android Application Model I

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs

CMSC436: Fall 2013 Week 3 Lab

ANDROID MOCK TEST ANDROID MOCK TEST IV

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

External Services. CSE 5236: Mobile Application Development Course Coordinator: Dr. Rajiv Ramnath Instructor: Adam C. Champion

COLLEGE OF ENGINEERING, NASHIK-4

Topics of Discussion

Real-Time Embedded Systems

COSC 3P97 Mobile Computing

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Android CardView Tutorial

Comp 595MC/L: Mobile Computing CSUN Computer Science Department Fall 2013 Midterm

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

Lecture 2 Android SDK

Embedded Systems Programming - PA8001

MC Android Programming

Integrated development environment (IDE), 16 Intent explicit intents, 37 filters, 37

Xin Pan. CSCI Fall

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

Mobile Application Development MyRent Settings

Transcription:

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 2

Fragment A Fragment represents a behavior or a portion of user interface in an Activity. Multiple fragments can be combined in a single activity to build a multi-pane UI and a fragment can be reused in multiple activities. A fragment is a modular section of an activity, which has its own lifecycle,receives its own input events and which can be added or removed while the activity is running (sort of like a "sub activity" that you can reuse in different activities). The Minimum Required Sdk should be the API 11 or larger, because Android introduced fragments in Android 3.0 Honeycomb (API level 11). 3

Fragment Idea You might decide to run a tablet in portrait mode with the handset model of only one fragment in an Activity 4

Fragment Lifecycle onattach(activity) called once the fragment is associated with its activity. oncreate(bundle) called to do initial creation of the fragment. oncreateview(layoutinflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onactivitycreated(bundle) tells the fragment that its activity has completed its own Activity.onCreate. onstart() makes the fragment visible to the user (based on its containing activity being started). onresume() makes the fragment interacting with the user (based on its containing activity being resumed). 5

Fragment Lifecycle As a fragment is no longer being used, it goes through a reverse series of callbacks: onpause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity. onstop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity. ondestroyview() allows the fragment to clean up resources associated with its View. ondestroy() called to do final cleanup of the fragment's state. ondetach() called immediately prior to the fragment no longer being associated with its activity. 6

Activity Lifecycle influences Activity paused: all its fragments paused Activity destroyed : all its fragments destroyed Activity running: manipulate each fragment independently. 7

Fragment: Classes android.app.fragment :The base class for all fragment definitions android.app.fragmentmanager :The class for interacting with fragment objects inside an activity android.app.fragmenttransaction: The class for performing an atomic set of fragment operations 8

Defining a Fragment Extend android.app.fragment Must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore. CALL Back functions (like Activity) : examples oncreate(), onstart(), onpause(), and onstop(). 9

..Defining a Fragment Fragment lives in a ViewGroup inside the activity's view hierarchy Most fragments will have a UI and will have its own layout There may also be a fragment without its own UI as an invisible worker for the activity( called headless fragment) The oncreateview() method is called by Android once the fragment should create its user interface. Here you can inflate a layout via the inflate() method call of the Inflator object passed as a parameter to this method. There is no need to implement this method for headless fragments 10

Defining Fragment - Example Parent s Activity ViewGroup public static class ExampleFragment extends Fragment { @Override public View oncreateview(layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) { Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed // Inflate the layout for this fragment View view = inflater.inflate(r.layout.example_fragment, container, false); return view; } Have example_fragment.xml file that contains the layout This will be contained in resource layout folder. } 11

Adding Fragment to an Activity Via XML(Statically) Insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element Via CODE(Dynamically) At any time while activity is running, fragment may be added to activity using Fragment Manager and FragmentTransaction 12

Adding Fragment to an Activity: Via XML The easiest way to incorporate a fragment into an activity is by including it directly into the activity s layout file. This works well if the fragment should always be present in the layout. However, this approach does not allow you to dynamically remove the fragment at run-time. In the activity s layout file, simply use the <fragment> element where you want to include the fragment. Use the android:name attribute to provide the packagequalified class name of the fragment. Specify the layout attributes to control the size and position of the fragment. 13

Adding fragment to an Activity thru XML layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.news.articlelistfragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" 2 fragment classes android:layout_height="match_parent" /> <fragment android:name="com.example.news.articlereaderfragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> Need unique ids for each so system can restore the fragment if the activity is restarted 14

Adding Fragment to an Activity: Via Code At any time while activity is running, fragments can be added to activity layout The activity layout must include a container View in which you can insert the fragment. Instantiate an instance of your fragment. Get a reference to the FragmentManager using Activity.getFragmentManager() Invoke FragmentManager.beginTransaction() to get an instance of FragmentTransaction. Use the FragmentTransaction.add() to add the fragment to a ViewGroup in the activity, specified by its ID. Optionally, a string tag can be provided to identify the fragment. Commit the transaction using FragmentTransaction.commit(). 15

Adding fragment to an Activity via CODE /*Inside Activity Code where you want to add Fragment (dynamically anywhere or in oncreate() callback) */ //get FragmentTransaction associated with this Activity FragmentManager fragmentmanager = getfragmentmanager(); FragmentTransaction fragmenttransaction = fragmentmanager.begintransaction(); //Create instance of your Fragment ExampleFragment fragment = new ExampleFragment(); This points to the Activity ViewGroup in which the fragment should be placed, //Add Fragment instance to your Activity specified by resource ID fragmenttransaction.add(r.id.fragment_container, fragment); fragmenttransaction.commit(); 16

Fragment Transactions adding, removing and replacing dynamically // Create new fragment and transaction Fragment newfragment = new ExampleFragment(); FragmentTransaction transaction getfragmentmanager().begintransaction(); // Replace whatever is in the fragment_container view with this fragment // and add the transaction to the back stack transaction.replace(r.id.fragment_container, newfragment); transaction.addtobackstack(null); // Commit the transaction transaction.commit(); newfragment replaces whatever fragment (if any) is currently in the layout container identified by the R.id.fragment_container If you do not call addtobackstack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addtobackstack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back. 17

Adding Fragment that has NO UI A fragment is also used to provide a background behavior for the activity without presenting additional UI It's not associated with a view in the activity layout, it does not receive a call to oncreateview(). So you don't need to implement that method. Use fragement to activity using FragmentTransaction.add(Fragment, String) (supplying a unique string "tag" for the fragment, rather than a view ID) If you want to get the fragment from the activity later, you need to use findfragmentbytag(). 18

FragmentManager methods: Get fragments that exist in Activity = findfragmentbyid() (for fragments that provide a UI in the activity layout) findfragmentbytag() (for fragments that do or don't provide a UI). Pop fragments off the back stack, popbackstack() (simulating a Back command by the user). Register a listener for changes to the back stack, addonbackstackchangedlistener(). 19

FragmentTransaction class Methods add() Add a fragment to the activity. remove() Remove a fragment from the activity. This operation destroys the fragment instance unless the transaction is added to the transaction back stack, described later. replace() Remove one fragment from the UI and replace it with another. hide() Hide a fragment in the UI (set its visibility to hidden without destroying the view hierarchy). show() Show a previously hidden fragment. detach() (API 13) Detach a fragment from the UI, destroying its view hierarchy but retaining the fragment instance. attach() (API 13) Reattach a fragment that has previously been detached from the UI, re-creating its view hierarchy. 20

Fragment-to-Fragment Communication All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity The Fragment captures the interface implementation during its onattach() lifecycle method and can then call the Interface methods in order to communicate with the Activity The host activity can deliver messages to a fragment by capturing the Fragment instance with findfragmentbyid(), then directly call the fragment's public methods 21

Fragment Sub-classes DialogFragment Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment ListFragment Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onlistitemclick() callback to handle click events PreferenceFragment Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" activity for your application WebViewFragment: Display a web view 22