Friday, October 21, 2016

Fragments 101 building better user interfaces

Fragments 101 building better user interfaces


android fragments android studio screenshot-16x9-720p

Android is an exciting platform to develop for, but it does have one major limitation: you can only display a single Activity onscreen at any one time (true, the upcoming Multi-Window mode does seem set to shake things up a bit, but well get to that shortly).

Thats where fragments come in.

Ever since Android 3.0, fragments have given developers a way of dividing their apps user interface into multiple, self-contained blocks, and then displaying these blocks in the way that makes sense for the users current screen configuration.

When you include fragments in your application, your app can either display these fragments:

  • One at a time in separate activities, in whats known as single-pane mode.
  • Side-by-side in a single Activity, in whats known as multi-pane mode.

For example, if you use fragments your app may choose to display a single fragment on a handset thats held in portrait mode, and then display two fragments side-by-side on a tablet-sized device – or, it may even switch to multi-pane mode when the user tilts that aforementioned handset from portrait mode, into landscape mode.

featuredSee also: Using CoordinatorLayout in Android apps1

This is where the real value of fragments lie: they give you a way of designing a single UI thats flexible enough to adapt to a wide range of different screen configurations. Thanks to the magic of fragments, you can sleep soundly at night knowing that your app is providing a good user experience, regardless of the kind of device it winds up on.

So what is a fragment, exactly?

Lets look at an example. Imagine you have a single Activity (the imaginatively-titled Activity A) and two fragments (Fragment 1 and Fragment 2).

Fragment 1 displays a list of nearby tourist attractions the user might want to visit. When the user selects an item from this list, Fragment B displays information about the currently-selected attraction.

Depending on the current screen configuration, your app may display these fragments in the following ways:

  • If the users screen is large enough, Activity A will display Fragment 1 and Fragment 2 side-by-side, in a multi-pane layout.
  • If there isnt enough room to accommodate both fragments, the app displays each fragment separately. In this scenario, Activity A displays Fragment 1 only. When the user selects an item from Fragment 1, the app creates a new Activity (lets call it Activity B) whose sole purpose in life is to host Fragment B.

Where does Multi-Window mode fit into all of this?

At this point you may be wondering: whats the difference between fragments and Nougats Multi-Window mode?

Android 7.0 seems set to address some of the platforms one-Activity-at-a-time limitations, but theres a crucial difference between fragments and Multi-Window:

  • Multi-Window will allow Android users to view Activities from different applications side-by-side.
  • Fragments give developers a way of displaying different content within a single application, depending on the users current screen configuration.

What you need to know before using fragments

When used correctly, fragments are a powerful tool in the Android developers arsenal, but if youre going to get the most out of fragments theres a couple of things you need to bear in mind:

1. A fragment is closely tied to its host Activity

A fragment may have its own behaviour, user interface and (to a certain extent) its own lifecycle, but it can only ever exist inside a host Activity. In fact, let me clarify that point about a fragments lifecycle: you can only add and remove fragments when the host Activity is in its resumed state. This means that even though a fragment does have a distinct lifecycle, that lifecycle is dependent on the lifecycle of its host Activity.

For the sake of keeping this tutorial (relatively) punchy, Im only going to look at how to add a fragment to an Activity declaratively, as this is the quickest and easiest way of getting started with fragments. The downside to this particular method, is that you wont be able to add and remove this fragment at runtime – if this is your end goal, then youll need to delve into your applications code (and the official Android docs has lots of useful info on this).

2. Backwards compatibility

If you want your app to connect with the largest possible audience (and who wouldnt want that?) then it has to be compatible with as many different versions of the Android operating system as possible. The good news is that, even though fragments didnt find their way into Android until Honeycomb, you can use fragments in your project while remaining backwards compatible with Android 1.6 and higher, thanks to the Android Support Library v4.

To add this Support Library to your project, launch the Android SDK Manager, select the SDK Tools tab and download the Android Support Repository.

fragments - android sdk manager-16x9

Next, add the library to your project by opening its module-level build.gradle file and adding the following to its dependencies section:

 dependencies { ……… ……… ……… compile com.android.support:appcompat-v7:24.0.0 } 

This is all you need to do for now, but just be aware that when you come to create your host Activity youll need to do the following:

  • Extend FragmentActivity, instead of the usual Activity class.
  • Import the android.support.v4.app.Fragment class.

Ill come back to both of these points when were looking at how to create your first Android fragment – which conveniently, just-so-happens to be the subject of our next section.

Creating a Fragment

Although you can create invisible fragments that contribute background behaviour but dont contribute a UI component, most fragments do have a user interface, so Im going to kick things off by defining my fragments UI.

In Android Studio, create a new layout file by opening your projects app/res folder, and then right-clicking the layout folder and selecting New, followed by Layout resource file.

fragments - new layout resource file-16x9
Give your layout resource file a name (Im going to use list_fragment) and select the root element you want to use, such as LinearLayout or RelativeLayout.

fragments - new resource file window-16x9
Click OK and Android Studio will go ahead and create your layout resource file. At this point you can add whatever UI elements you want to include in your fragment. Im going to use the following:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout  android_orientation="vertical" android_layout_width="match_parent" android_layout_height="wrap_content" android_background="#CCCCCC"> <TextView android_layout_width="wrap_content" android_layout_height="wrap_content" android_textSize="30sp" android_textStyle="bold" android_textColor="#ffffff" android_text="This is the contents of my list_fragment.xml" android_id="@+id/textView2" android_layout_gravity="center_horizontal" /> </LinearLayout> 

As well as a UI component, you need to have a class associated with your fragment. To create a new class, open your projects app/Java folder, right-click its package name and select New, followed by Java Class.

fragments - new java class-16x9
Give your new class a name (Im going to use ListFragment), then open your new class file and make the following changes:

 import android.os.Bundle; //If you want your app to be compatible with devices running Android 1.6 and earlier, //you need to import the fragment class from the v4 support library// import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; //Since Im targeting devices running Android 1.6 and higher, //Im going to extend FragmentActivity, rather than the usual Activity class// public class ListFragment extends FragmentActivity { @Override //onCreateView() must return a View, which is the root of your fragments layout// public View onCreateView(LayoutInflater inflater, ViewGroup container, //If the fragment is being resumed, savedInstanceState will pass data //about the previous instance of the fragment// Bundle savedInstanceState) { //Inflate the fragments layout resource file// return inflater.inflate(R.layout.list_fragment, container, false); } } 

The final step is adding this fragment to your Activity. As already mentioned, there are two ways of doing this, but in this article Im only going to look at adding the fragment declaratively by embedding it in the host Activitys layout resource file.

To add a fragment to an Activity, simply open that Activitys corresponding layout resource file and declare the fragment you want to use, in exactly the same way youd declare a View. So you have no problems distinguishing between the portion of the finished UI thats contributed by the activity_main.xml file, and the portion thats contributed by the fragment, Im going to set activity_main to display an image:

 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout   android_layout_width="match_parent" android_layout_height="match_parent" android_background="@drawable/background" tools_context="com.fragmentsexample.jessicathornsby.myapplication.MainActivity"> //Add your fragment// <fragment android_name="com.fragmentsexample.jessicathornsby.myapplication.ListFragment" android_id="@+id/list_fragment" android_layout_width="match_parent" android_layout_height="wrap_content" /> </RelativeLayoutLayout> 

Wrap-up

And thats it! The full source code for the demo app can be found on GitHub. How have you used fragments in your own Android app projects? Let us know in the comments.



from Android Authority http://ift.tt/2ak1cKN
via IFTTT

Available link for download