Android Development 17

Android Fragments TutorialWelcome to part 17 of my Android Development Tutorial. This is part 2 of my Android Fragments Tutorial series. Part 1 is here and you should watch it before watching this video.

Fragments are often used so you can create completely different interfaces depending upon the screen real estate available. We’ll cover how to do that and we’ll also look at how we can get the fragments to communicate with each other and the main activity. The Whole package is available here Android Fragments.

If you like videos like this, it helps to tell Google+ with a click here

Code From the Video


// Contains the fake data to display for both headlines
// and articles

public class Ipsum {

    static String[] Headlines = {
        "Article One",
        "Article Two"

    static String[] Articles = {
        "Article One\n\nExcepteur pour-over occaecat squid biodiesel" + 
        "umami gastropub, nulla laborum salvia dreamcatcher fanny pack." + 
        "Ullamco culpa retro ea, trust fund excepteur eiusmod direct trade" + 
        "banksy nisi lo-fi cray messenger bag. Nesciunt esse carles selvage" + 
        "put a bird on it gluten-free, wes anderson ut trust fund twee occupy" + 
        "viral. Laboris small batch scenester pork belly, leggings ut farm-to-table" + 
        "aliquip yr nostrud iphone viral next level. Craft beer dreamcatcher" + 
        "pinterest truffaut ethnic, authentic brunch. Esse single-origin coffee" + 
        "banksy do next level tempor. Velit synth dreamcatcher, magna shoreditch" + 
        "in american apparel messenger bag narwhal PBR ennui farm-to-table.",
        "Article Two\n\nVinyl williamsburg non velit, master cleanse four loko" + 
        "banh mi. Enim kogi keytar trust fund pop-up portland gentrify. Non ea" + 
        "typewriter dolore deserunt Austin. Ad magna ethical kogi mixtape next" + 
        "level. Aliqua pork belly thundercats, ut pop-up tattooed dreamcatcher" + 
        "kogi accusamus photo booth irony portland. Semiotics brunch ut locavore" + 
        "irure, enim etsy laborum stumptown carles gentrify post-ironic cray." + 
        "Butcher 3 wolf moon blog synth, vegan carles odd future."


<?xml version="1.0" encoding="utf-8"?>
    <dimen name="article_view_padding">16dp</dimen>
    <dimen name="article_view_text_size">18sp</dimen>


<?xml version="1.0" encoding="utf-8"?>
<!-- This FrameLayout blocks off part of the screen and then puts
	a ListView and group of List Items representing each article.
	The size of the FrameLayout is the size of its largest child -->
<FrameLayout xmlns:android=""
    android:layout_height="match_parent" />


<?xml version="1.0" encoding="utf-8"?>
<!-- Will hold the selected article text -->
<TextView xmlns:android=""
    android:textSize="@dimen/article_view_text_size" />

news_articles.xml (layout-large)

<?xml version="1.0" encoding="utf-8"?>
<!-- Used in layout-large folder -->
<LinearLayout xmlns:android=""

    <fragment android:name=""
              android:layout_height="match_parent" />

    <fragment android:name=""
              android:layout_height="match_parent" />



import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

// A ListFragment is used to display a list of items

public class HeadlinesFragment extends ListFragment {
	// Will monitor if a headline is clicked on
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the 
    // fragment can deliver messages
    public interface OnHeadlineSelectedListener {
        // This function is called when a list item is selected
        public void onArticleSelected(int position);

    // Initializes the Fragment
    public void onCreate(Bundle savedInstanceState) {

        int layout = android.R.layout.simple_list_item_1;
        // A ListAdapter populates the ListView with data in ipsum arrays
        // An ArrayAdapter specifically deals with arrays
        // getActivity() gets an Intent to start a new activity
        // layout is the list items layout
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
    // Called when the Fragment is visible on the screen

    public void onStart() {

        // If we have both the article names and the article Fragments on the screen
        // at the same time we highlight the selected article
        // The getFragmentManager() returns the FragmentManager which allows us
        // to interact with Fragments associated with the current activity
        // getListView() gets a ListView 
        //  CHOICE_MODE_SINGLE allows up to one item to be in a chosen state in the list
        if (getFragmentManager().findFragmentById( != null) {

    // Called when a Fragment is attached to an Activity

    public void onAttach(Activity 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");

    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

//To auto import unimplemented methods
//Right Click class - Source - Override/Implement Methods
//Check what to implement

public class ArticleFragment extends Fragment {
	// Used to pass the current article selected between activities
    final static String ARG_POSITION = "position";
    // Used to track the current article in this class
    int mCurrentPosition = -1;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) {

        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);

    public void onStart() {

        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        // Check if an article had been selected
        if (args != null) {
            // Set article based on argument passed in
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
    // Put the text for the selected article in the article TextView

    public void updateArticleView(int position) {
        TextView article = (TextView) getActivity().findViewById(;
        mCurrentPosition = position;

    public void onSaveInstanceState(Bundle outState) {

        // Save the current article selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);

 * Copyright (C) 2012 The Android Open Source Project
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

import android.os.Bundle;

// A fragment is a kind of sub-activity that you can add or
// remove from other activities while the activity continues
// to run. 

// We extend the FragmentActivity to be able to use Fragments
// on platforms prior to Android 3.0

public class MainActivity extends FragmentActivity 
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    // Called when the activity is first created
    public void onCreate(Bundle savedInstanceState) {

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById( != 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) {

            // Create an instance of the Fragment that holds the titles
            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

            // Add the fragment to the 'fragment_container' FrameLayout
            // beginTransaction() is used to begin any edits of Fragments
                    .add(, firstFragment).commit();

    // Required if the OnHeadlineSelectedListener interface is implemented
    // This method is called when a headline is clicked on
    public void onArticleSelected(int position) {

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)

        // If the article fragment is here we're in the two pane layout

        if (articleFrag != null) {
            // Get the ArticleFragment to update itself

        } else {
            // If the fragment is not available, use the one pane layout and 
        	// swap between the article and headline fragments

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            // The Bundle contains information passed between activities
            Bundle args = new Bundle();
            // Save the current article value
            args.putInt(ArticleFragment.ARG_POSITION, position);
            // Add the article value to the new Fragment
            // The FragmentTransaction adds, removes, replaces and
            // defines animations for Fragments
            // The FragmentManager provides methods for interacting
            // beginTransaction() is used to begin any edits of Fragments
            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(, newFragment);
            // addToBackStack() causes the transaction to be remembered. 
            // It will reverse this operation when it is later popped off 
            // the stack.

            // Schedules for the addition of the Fragment to occur

54 Responses to “Android Development 17”

  1. Josh says:


    Thanks for tutorials. Can you please make one tutorial about AlarmManager and how to set multiple alarms?

  2. amar says:

    what is the different btwn app made in JAVA and app made in JAVA EE ..

    • Derek Banas says:

      A Android Java app would be able to take advantage of all the specific Android tools. An app meant to be cross platform would work on more devices, but lose access to those tools specific to either Android or iOS

  3. Anonymous says:

    Master Derek, can you make an android tutorial about reading images? like inputing a string to match the name of the image and if he got the correct string or the name of the image, the user can guess another image again. I hope you understood what I typed, hehe, thanks a million if you’ll make a tutorial of my request, and even if you don’t, thanks for the great tuts πŸ™‚

  4. amar says:

    Nw amazon has made one tool for developing android app using html5 ..
    People say its better den any other tool and easy to make app..
    is it true?????

  5. sbo says:

    hi derek, i know you busy with c tutorials, but i was hoping if u could squeeze in a gesture tutorial for andriod.
    thanks for everything.

  6. Mohammmed Isa says:

    why do we need this line of code in
    i didn’t get this point, since we are not using any intents here.

  7. amar says:

    I wnt to know frm u derek..
    That phone gap is much easier or directly frm eclipse its will be easier for us to develope android app..

  8. Grant says:

    Hi Derek,

    Thanks for the awesome tutorials, are you going to be posting some more android stuff? I’m trying to figure out the process of an android app interacting with a restful service, will you be covering that?

    • Derek Banas says:

      You’re very welcome πŸ™‚ Yes more Android tutorials are coming. I’ll get them out ASAP. I covered how to use the Yahoo restful service for XML and JSON early in the tutorial. I will cover how to create webservices soon.

  9. My (humble) requests are

    animations (simple game)
    rotation handling

    Thanks for all your wonderful material!

  10. Muthusi says:

    Hey …love the tutorials so helping me learn android …gat a sem project that i have to make a fashion app could you plse cover colour selection ..would be so helpfull thanks man

    • Derek Banas says:

      I’m going to spend more time on interface design soon. Sorry the videos are taking so long. I’m trying to make sure each one is good. I have been throwing a bunch of the videos out.

  11. Enrique says:

    Master, I’m from Nicaragua and I do not know if you speak spanish but if you do let me know and if you do not, it is ok, Because I’m learning it, well I got a question in the tutorial number 3 I made and follow all the step for the app, but at the end of running the app to my device, which is a tablet mediapad 7 lite, an error appears like the app “crazytipcalc has stopped”, and the option ok to exit, I do not know was the problem is, and thank you for the tutorials is a such a wonderfull website

    • Derek Banas says:

      Thank you πŸ™‚ I speak a little Spanish, but I use a translator if I need to.

      As per your question, what errors are you getting in the LogCat panel in Eclipse? (Window -> Show View -> Other… -> Android -> LogCat)

  12. 谒谒你。

  13. Henry says:

    Hello Derek, thank you so much for the amazing tutorials. Do u know how to make Dictionary app. Where people can type word like “computer’ and get the meaning/definition of computer. I would like to make English to my native language dictionary and it is very important. I have been following your tutorials hoping i would learn how to make dictionary app at least in the end. Could you please teach me how to do that? thank you very much.

    • Derek Banas says:

      I actually was going to make an app that would act as a universal translator. My approach was to build the translations using the Grammatical Framework.

      The app quickly got out of control, teaching wise, so I had to drop the idea for a tutorial. You could definitely make a translation app this way though. I’d be very interested in what you come up with.

      I hope that helps πŸ™‚

      • Henry says:

        Hello Derek,

        Thanks for ur kind reply. Sadly i have very basic knowledge of programming. Could u point me to other source links if u know. I have all the list of 5000 words and meaning already in excel file. I need some way to extract this file when people make query in app form. Thanks you.

  14. Max says:

    Salut Derek,
    The first, I really love your videos. Thank you for your sharing!
    And second, i have problem with this fragment tutorial. I try to code by myself or copy direct your source codes to my eclipse but it’s still not worked …!

    The application force close when i try to open it
    This is logcat error:
    E/AndroidRuntime(2197): Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f030003

    I think have some problem with onCreate method in MainActivity. But i can’t fix it. I tried clean project and then restart eclipse. I didn’t find any answer from google or stackoverflow also. Could you help me please ! Thanks again.

  15. Adam says:

    Hi Derek,

    Thank you for the wonderful tutorials and you are the best.

    I am wondering if you have or will you be covering tabs in future. I have not covered all tutorials yet could you please let me know the number if you did.

    Thank you very much,


  16. Hikari says:

    Why do I keep getting this error very frequently?! “The specified activity does not exist! Getting the launcher activity.”
    The codes are exactly the same.

  17. Prince Soni says:

    But I would like to point out one thing I noticed. Now a days your video tutorials like this one is very very fast you use copy paste of code a lot and you are damm fast.

    For instance I need to pause this video after each minute to write out the codes you have written.

    of course you have provided the code along with comments but still I like to make programs along with live video tutorials so please if you can slow down, In this video you were really too fast and it was not at all enjoyable writing with you

    Thnx for providing these awesome tutorials

  18. Prince Soni says:

    Hey, Your tutorials study materials are awesome, I don’t have words to thank u. The content of your video tutorials are just amazzzing.

    • Prince Soni says:

      Hey Derek why not make a wonderful app, at the end of which there is also a walk through to upload it to google play store. ( Please do not choose google maps as the major app video tutorial – it sucks ).

      Thnks anyway

      • Derek Banas says:

        Eventually I’m going to great apps to go along with the video tutorials. So for example if I do an algebra tutorial I will make an Algebra practice app. I plan to do this over and over again. That way I can teach how to make real world Android apps while I continue to explore new areas of knowledge. Everything will be free πŸ™‚

    • Derek Banas says:

      Thank you for the kind words πŸ™‚ I try to do my best.

  19. Gilles says:

    First of all thanks for your tutorial.
    To test this app on my Galaxy S4, I replaced layout-large by layout-land. But when I select an article in land layout, I have a NullPointerException in updateArticleView because article was not found.
    Is it a little bug or is it because it has to be implemented another way when one uses layout-land ?
    Thanks in advance for your answer.


  20. hero says:

    I really wanna understand this tutorial. But everything seem not very easy to be understood for me. teacher Derek, can you tell me how to understand this source codes fully please? Thank you very much

  21. ricky says:

    Hello Derek, what is the preferable resolution for this lab. My first emulator is to small to have these landscape changes. Then I changed to a Nexus 10 with a 2560*1600 it’s so big that it only has the landscape. Thanks for very good tutorials.

  22. Daniel says:

    I’m trying to figure out fragments… and this example still leaves me with a question.

    * When this app is started on a large device, the first entry to source code is to onAttach in

    * When this app is started on a small device, the first entry to source code is to onCreate in

    Ok – I understand if the large layout is used, it calls fragments, and if the smaller layout is used, well, it isn’t used until inflates it.

    So, why/how does android know that if using the large xml, to call using the fragment lifecycle (which starts with onAttach in, and if using the small device, to use the activity lifecycle (that starts with onCreate in

    Thanks in advance for your help.

    And by the way… FANTASTIC TUTORIALS!!!!!!!!!!!!

  23. Daniel says:

    Ok… figured it out. My previous post isn’t exactly accurate… so this is what I found out.

    When run on a large device, the order of what is run is:

    *, onCreate starts
    when setContentView is executed, the following gets run:
    *, OnAttached gets called
    *, OnCreate gets called
    *, OnCreateView gets called
    *, onCreate ends
    *, onStart gets called
    *, onStart gets called
    * Tablet screen now shows both fragments.

    On the other hand, a much different path happens if a SMALL device screen is run:

    *, onCreate starts
    * if statement starts FragmentManager and begins Fragment.add…
    *, onCreate ends
    *, onAttach is called
    *, onCreate is called
    *, onStart is called
    * Phone screen now shows headlines fragment only.

    So what it comes down to is: When setContentView is called, if the layout contains fragments (as in the large device), the fragments get started. If setContentView does not contain fragments (as in the small device), nothing was started, so the Activity needs to start the fragments it wants/needs.

    I now see it’s obvious… now…


    Thanks – Daniel

Leave a Reply

Your email address will not be published.