Android 16: Fragments: Tutorial

Slides:



Advertisements
Similar presentations
Programming with Android: Android for Tablets Luca Bedogni Marco Di Felice Dipartimento di Scienze dellInformazione Università di Bologna.
Advertisements

Programming with Android: Android for Tablets Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Fragments: Introduction Fragments were introduced in Android 3.0 to support flexible and dynamic UI designs represent portions of an application’s user.
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Filip Debelić What is it? Android is a mobile operating system (OS) based on the Linux kernel and currently developed by Google Android,
Android Fragments.
Presented by IBM developer Works ibm.com/developerworks/ 2006 January – April © 2006 IBM Corporation. Making the most of Creating Eclipse plug-ins.
Programming with Android: Android Fragments Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Android Fragments A very brief introduction Android Fragments1.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
Better reference the original webpage :
ANDROID UI – FRAGMENTS. Fragment  An activity is a container for views  When you have a larger screen device than a phone –like a tablet it can look.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Basic Android Tutorial USF’s Association for Computing Machinery.
Mobile Programming Lecture 6
DUE Hello World on the Android Platform.
INTRODUCTION TO ANDROID. Slide 2 Application Components An Android application is made of up one or more of the following components Activities We will.
Android – Fragments L. Grewe.
Cosc 4730 Android Fragments. Fragments You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own.
ANDROID APPLICATION DEVELOPMENT. ANDROID DEVELOPMENT DEVELOPER.ANDROID.COM/INDEX.HTML THE OFFICIAL SITE FOR ANDROID DEVELOPERS. PROVIDES THE ANDROID SDK.
TCS Internal Maps. 2 TCS Internal Objective Objective :  MAPS o Integration of Maps.
Class on Fragments & threads. Fragments fragment is a modular section of an activity, which has its own lifecycle, receives its own input events, and.
CHAPTER 4 Fragments ActionBar Menus. Explore how to build applications that use an ActionBar and Fragments Understand the Fragment lifecycle Learn to.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Android Fragments. Slide 2 Lecture Overview Getting resources and configuration information Conceptualizing the Back Stack Introduction to fragments.
Introduction to Android Programming
Fragments and Menus Chapter 4 1. Objectives Learn three different types of menus: options, context, and popup Learn to configure the ActionBar and Toolbar.
Lab7 – Appendix.
Introduction to android
Android Application -Architecture.
Android 01: Fundamentals
Location-Based Services: Part 2 (Google Maps)
Activity and Fragment.
CS240: Advanced Programming Concepts
Instructor: Mazhar Hussain
Android – Event Handling
Android Studio, Android System Basics and Git
Activities, Fragments, and Events
Fragment ?.
Fragments: Introduction
Android 3: Fragments: API Guide
CS499 – Mobile Application Development
Mobile Application Development BSCS-7 Lecture # 6
Mobile Applications (Android Programming)
Activities and Intents
Widgets & Fragments Kalin Kadiev Astea Solutions AD.
Mobile Application Development Chapter 4 [Android Navigation and Interface Design] IT448-Fall 2017 IT448- Fall2017.
Android 15: Fragments: API Guide
The Android Activity Lifecycle
Mobile Application Development BSCS-7 Lecture # 11
Android 15: Settings Kirk Scott.
Android – Fragments L. Grewe.
ANDROID UI – FRAGMENTS UNIT II.
CIS 470 Mobile App Development
Chapter 9: Fragments.
Activities and Intents
Activities and Intents
CIS 470 Mobile App Development
Android Application Development
CIS 470 Mobile App Development
Emerging Platform#3 Android & Programming an App
Mobile Programming Dr. Mohsin Ali Memon.
Activities and Fragments
CS 240 – Advanced Programming Concepts
Android Development Tools
Preference Activity class
Activities, Fragments, and Intents
Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Android 16: Fragments: Tutorial Kirk Scott

Introduction The most recent sets of overheads have been taken from the Android API Guides This set of overheads returns to the API Training Working through the online documentation, it has become increasingly apparent that various kinds of functionality in Android are implemented with fragments It’s time to find out more about what they are

Outline 15.1 Creating a Fragment—Starting Out 15.2 Support Library Setup 15.3 Creating a Fragment—Continuing 15.4 Building a Flexible UI 15.5 Communicating with Other Fragments

15.1 Creating a Fragment—Starting Out

Creating a Fragment You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

This lesson shows how to extend the Fragment class using the Support Library so your app remains compatible with devices running system versions as low as Android 1.6.

Before you begin this lesson, you must set up your Android project to use the Support Library. If you have not used the Support Library before, set up your project to use the v4 library by following the Support Library Setup document.

However, you can also include the app bar in your activities by instead using the v7 appcompat library, which is compatible with Android 2.1 (API level 7) and also includes the Fragment APIs.

15.2 Support Library Setup

Support Library Setup How you setup the Android Support Libraries in your development project depends on what features you want to use and what range of Android platform versions you want to support with your application. This document guides you through downloading the Support Library package and adding libraries to your development environment.

Downloading the Support Libraries The Android Support Repository package is provided as a supplemental download to the Android SDK and is available through the Android SDK Manager. Follow the instructions below to obtain the Support Library files.

To download the Support Library through the SDK Manager: 1. Start the Android SDK Manager. 2. In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder and, if necessary, expand to show its contents. 3. Select the Android Support Repository item. 4. Click the Install packages... button. [See the following overhead]

Figure 1. The Android SDK Manager with Android Support Repository selected.

After downloading, the tool installs the Support Library files to your existing Android SDK directory. The library files are located in the following subdirectory of your SDK: <sdk>/extras/android/m2repository/com/android/support/ directory.

Choosing Support Libraries Before adding a Support Library to your application, decide what features you want to include and the lowest Android versions you want to support. For more information on the features provided by the different libraries, see Support Library Features.

Adding Support Libraries In order to use a Support Library, you must modify your application's project's classpath dependencies within your development environment. You must perform this procedure for each Support Library you want to use.

To add a Support Library to your application project: 1. Make sure you have downloaded the Android Support Repository using the SDK Manager. 2. Open the build.gradle file for your application. 3. Add the support library to the dependencies section.

For example, to add the v4 core-utils library, add the following lines: dependencies {     ...     compile "com.android.support:support-core-utils:24.2.0" }

Caution: Using dynamic dependencies (for example, palette-v7:23 Caution: Using dynamic dependencies (for example, palette-v7:23.0.+) can cause unexpected version updates and regression incompatibilities. We recommend that you explicitly specify a library version (for example, palette-v7:24.2.0).

Using Support Library APIs Support Library classes that provide support for existing framework APIs typically have the same name as framework class but are located in the android.support class packages, or have a *Compat suffix.

Caution: When using classes from the Support Library, be certain you import the class from the appropriate package. For example, when applying the ActionBar class: android.support.v7.app.ActionBar when using the Support Library. android.app.ActionBar when developing only for API level 11 or higher.

Note: After including the Support Library in your application project, we strongly recommend using the ProGuard tool to prepare your application APK for release. In addition to protecting your source code, the ProGuard tool also removes unused classes from any libraries you include in your application, which keeps the download size of your application as small as possible. For more information, see ProGuard.

Further guidance for using some Support Library features is provided in the Android developer training classes, guides and samples. For more information about the individual Support Library classes and methods, see the android.support packages in the API reference.

Manifest Declaration Changes If you are increasing the backward compatibility of your existing application to an earlier version of the Android API with the Support Library, make sure to update your application's manifest. Specifically, you should update the android:minSdkVersion element of the <uses-sdk> tag in the manifest to the new, lower version number, as shown below: [See the following overhead]

  <uses-sdk       android:minSdkVersion="14"       android:targetSdkVersion="23" />

The manifest setting tells Google Play that your application can be installed on devices with Android 4.0 (API level 14) and higher. If you are using Gradle build files, the minSdkVersion setting in the build file overrides the manifest settings. [See the following overhead]

apply plugin: 'com. android. application' android { apply plugin: 'com.android.application' android {     ...     defaultConfig {         minSdkVersion 16         ...     }     ... }

In this case, the build file setting tells Google Play that the default build variant of your application can be installed on devices with Android 4.1 (API level 16) and higher. For more information about build variants, see Build System Overview.

Note: If you are including several support libraries, the minimum SDK version must be the highest version required by any of the specified libraries. For example, if your app includes both the v14 Preference Support library and the v17 Leanback library, your minimum SDK version must be 17 or higher.

15.3 Creating a Fragment—Continuing

Create a Fragment Class To create a fragment, extend the Fragment class, then override key lifecycle methods to insert your app logic, similar to the way you would with an Activity class.

One difference when creating a Fragment is that you must use the onCreateView() callback to define the layout. In fact, this is the only callback you need in order to get a fragment running. For example, here's a simple fragment that specifies its own layout: [See the following overhead and notice in particular the import out of the support library]

import android. os. Bundle; import android. support. v4. app import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.ViewGroup; public class ArticleFragment extends Fragment {     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,         Bundle savedInstanceState) {         // Inflate the layout for this fragment         return inflater.inflate(R.layout.article_view, container, false);     } }

Just like an activity, a fragment should implement other lifecycle callbacks that allow you to manage its state as it is added or removed from the activity and as the activity transitions between its lifecycle states. For instance, when the activity's onPause() method is called, any fragments in the activity also receive a call to onPause().

More information about the fragment lifecycle and callback methods is available in the Fragments developer guide.

Add a Fragment to an Activity using XML While fragments are reusable, modular UI components, each instance of a Fragment class must be associated with a parent FragmentActivity. You can achieve this association by defining each fragment within your activity layout XML file.

Note: FragmentActivity is a special activity provided in the Support Library to handle fragments on system versions older than API level 11. If the lowest system version you support is API level 11 or higher, then you can use a regular Activity.

Here is an example layout file that adds two fragments to an activity when the device screen is considered "large" (specified by the large qualifier in the directory name). res/layout-large/news_articles.xml [See the following overhead]

<LinearLayout xmlns:android="http://schemas. android <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:orientation="horizontal"     android:layout_width="fill_parent"     android:layout_height="fill_parent">     <fragment android:name="com.example.android.fragments.HeadlinesFragment"               android:id="@+id/headlines_fragment"               android:layout_weight="1"               android:layout_width="0dp"               android:layout_height="match_parent" />     <fragment android:name="com.example.android.fragments.ArticleFragment"               android:id="@+id/article_fragment"               android:layout_weight="2"               android:layout_width="0dp"               android:layout_height="match_parent" /> </LinearLayout>

Tip: For more about creating layouts for different screen sizes, read Supporting Different Screen Sizes. Then apply the layout to your activity: [See the following overhead]

import android. os. Bundle; import android. support. v4. app import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity {     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.news_articles);     } }

If you're using the v7 appcompat library, your activity should instead extend AppCompatActivity, which is a subclass of FragmentActivity. For more information, read Adding the App Bar).

Note: When you add a fragment to an activity layout by defining the fragment in the layout XML file, you cannot remove the fragment at runtime. If you plan to swap your fragments in and out during user interaction, you must add the fragment to the activity when the activity first starts, as shown in the next lesson.

15.4 Building a Flexible UI

When designing your application to support a wide range of screen sizes, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space.

For example, on a handset device it might be appropriate to display just one fragment at a time for a single-pane user interface. Conversely, you may want to set fragments side-by-side on a tablet which has a wider screen size to display more information to the user.

Figure 1. Two fragments, displayed in different configurations for the same activity on different screen sizes. On a large screen, both fragments fit side by side, but on a handset device, only one fragment fits at a time so the fragments must replace each other as the user navigates.

The FragmentManager class provides methods that allow you to add, remove, and replace fragments to an activity at runtime in order to create a dynamic experience.

Add a Fragment to an Activity at Runtime Rather than defining the fragments for an activity in the layout file—as shown in the previous lesson with the <fragment> element—you can add a fragment to the activity during the activity runtime. This is necessary if you plan to change fragments during the life of the activity.

To perform a transaction such as add or remove a fragment, you must use the FragmentManager to create a FragmentTransaction, which provides APIs to add, remove, replace, and perform other fragment transactions.

If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity's onCreate() method. An important rule when dealing with fragments—especially when adding fragments at runtime—is that your activity layout must include a container View in which you can insert the fragment.

The following layout is an alternative to the layout shown in the previous lesson that shows only one fragment at a time. In order to replace one fragment with another, the activity's layout includes an empty FrameLayout that acts as the fragment container.

Notice that the filename is the same as the layout file in the previous lesson, but the layout directory does not have the large qualifier, so this layout is used when the device screen is smaller than large because the screen does not fit both fragments at the same time. res/layout/news_articles.xml: [See the following overhead]

<FrameLayout xmlns:android="http://schemas. android <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/fragment_container"     android:layout_width="match_parent"     android:layout_height="match_parent" />

Inside your activity, call getSupportFragmentManager() to get a FragmentManager using the Support Library APIs. Then call beginTransaction() to create a FragmentTransaction and call add() to add a fragment. You can perform multiple fragment transaction for the activity using the same FragmentTransaction.

When you're ready to make the changes, you must call commit(). For example, here's how to add a fragment to the previous layout: [See the following overheads]

import android. os. Bundle; import android. support. v4. app import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity {     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.news_articles);         // Check that the activity is using the layout version with         // the fragment_container FrameLayout         if (findViewById(R.id.fragment_container) != null) {             // However, if we're being restored from a previous state,             // then we don't need to do anything and should return or else             // we could end up with overlapping fragments.             if (savedInstanceState != null) {                 return;             }

            // Create a new Fragment to be placed in the activity layout             HeadlinesFragment firstFragment = new HeadlinesFragment();             // In case this activity was started with special instructions from an             // Intent, pass the Intent's extras to the fragment as arguments             firstFragment.setArguments(getIntent().getExtras());             // Add the fragment to the 'fragment_container' FrameLayout             getSupportFragmentManager().beginTransaction()                     .add(R.id.fragment_container, firstFragment).commit();         }     } }

Because the fragment has been added to the FrameLayout container at runtime—instead of defining it in the activity's layout with a <fragment> element—the activity can remove the fragment and replace it with a different one.

Replace One Fragment with Another The procedure to replace a fragment is similar to adding one, but requires the replace() method instead of add(). Keep in mind that when you perform fragment transactions, such as replace or remove one, it's often appropriate to allow the user to navigate backward and "undo" the change.

To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit the FragmentTransaction.

Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced.

Example of replacing one fragment with another: [See the following overhead]

// Create fragment and give it an argument specifying the article it should show ArticleFragment newFragment = new ArticleFragment(); Bundle args = new Bundle(); args.putInt(ArticleFragment.ARG_POSITION, position); newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();

The addToBackStack() method takes an optional string parameter that specifies a unique name for the transaction. The name isn't needed unless you plan to perform advanced fragment operations using the FragmentManager.BackStackEntry APIs.

15.5 Communicating with Other Fragments

In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that defines its own layout and behavior. Once you have defined these reusable Fragments, you can associate them with an Activity and connect them with the application logic to realize the overall composite UI.

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Define an Interface 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. Here is an example of Fragment to Activity communication: [See the following overhead]

public class HeadlinesFragment extends ListFragment {     OnHeadlineSelectedListener mCallback;     // Container Activity must implement this interface     public interface OnHeadlineSelectedListener {         public void onArticleSelected(int position);     }     @Override     public void onAttach(Activity activity) {         super.onAttach(activity);         // This makes sure that the container activity has implemented         // the callback interface. If not, it throws an exception         try {             mCallback = (OnHeadlineSelectedListener) activity;         } catch (ClassCastException e) {             throw new ClassCastException(activity.toString()                     + " must implement OnHeadlineSelectedListener");         }     }     ... }

Now the fragment can deliver messages to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface. For example, the following method in the fragment is called when the user clicks on a list item.

The fragment uses the callback interface to deliver the event to the parent activity.     @Override     public void onListItemClick(ListView l, View v, int position, long id) {         // Send the event to the host activity         mCallback.onArticleSelected(position);     }

Implement the Interface In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class. For example, the following activity implements the interface from the above example. [See the following overhead]

public static class MainActivity extends Activity         implements HeadlinesFragment.OnHeadlineSelectedListener{     ...     public void onArticleSelected(int position) {         // The user selected the headline of an article from the HeadlinesFragment         // Do something here to display that article     } }

Deliver a Message to a Fragment The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods. For instance, imagine that the activity shown above may contain another fragment that's used to display the item specified by the data returned in the above callback method.

In this case, the activity can pass the information received in the callback method to the other fragment that will display the item: [See the following overhead]

public static class MainActivity extends Activity         implements HeadlinesFragment.OnHeadlineSelectedListener{     ...     public void onArticleSelected(int position) {         // The user selected the headline of an article from the HeadlinesFragment         // Do something here to display that article         ArticleFragment articleFrag = (ArticleFragment)                 getSupportFragmentManager().findFragmentById(R.id.article_fragment);         if (articleFrag != null) {             // If article frag is available, we're in two-pane layout...             // Call a method in the ArticleFragment to update its content             articleFrag.updateArticleView(position);         } else {             // Otherwise, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article             ArticleFragment newFragment = new ArticleFragment();             Bundle args = new Bundle();             args.putInt(ArticleFragment.ARG_POSITION, position);             newFragment.setArguments(args);             FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();             // Replace whatever is in the fragment_container view with this fragment,             // and add the transaction to the back stack so the user can navigate back             transaction.replace(R.id.fragment_container, newFragment);             transaction.addToBackStack(null);             // Commit the transaction             transaction.commit();         }     } }

Summary and Mission This unit contained information on fragments given in the online training The previous set of overheads presented the API Guide information on fragments Although together they’re really still just introductory, that’s it for this topic There is no mission for this unit You may decide that you want to master fragments in order to earn homework points

The End