How to Make Android Apps 12

Android Fragment ExampleIn this tutorial I will provide another Android Fragment example. I have received a bunch of questions about a Android development Fragment example. So, here I’ll cover every line of code in it and I will also show how to change it so that it fits the requirements that many people want.

We’ll cover how to create horizontal and portrait layouts, ListViews, Array Adapters, onSaveInstanceState, ListView events, opening different layouts based on orientation.

If you like videos like this, it helps if you share on Google Plus with a click here

Code From the Video

package com.newthinktank.derekbanas.fragmentlayout;

import android.os.Bundle;

public class FragmentLayout extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

        // Set the layout for fragment_layout.xml



<FrameLayout xmlns:android=""
    android:layout_width="match_parent" android:layout_height="match_parent">
    <fragment class="com.newthinktank.derekbanas.fragmentlayout.TitlesFragment"
        android:layout_width="match_parent" android:layout_height="match_parent" />


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:layout_width="match_parent" android:layout_height="match_parent">
    <fragment class="com.newthinktank.derekbanas.fragmentlayout.TitlesFragment"

    <!-- FrameLayouts are used to block out a part of the screen to display normally a single
    detailsElementBackground is a background that can provide details about the data
    the user is selecting -->
    <FrameLayout android:id="@+id/details"


package com.newthinktank.derekbanas.fragmentlayout;

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

// Shows the title fragment which is a ListView
// When a ListView item is selected we will put the DetailsFragment in the 
// Framelayout if we are in horizontal mode, or we will create a DetailsActivity // and switch to it if in portrait mode
public class TitlesFragment extends ListFragment {

    // True or False depending on if we are in horizontal or duel pane mode
    boolean mDuelPane;

    // Currently selected item in the ListView
    int mCurCheckPosition = 0;

    public void onActivityCreated(Bundle savedInstanceState) {

        // An ArrayAdapter connects the array to our ListView
        // getActivity() returns a Context so we have the resources needed
        // We pass a default list item text view to put the data in and the 
        // array
        ArrayAdapter<String> connectArrayToListView = new ArrayAdapter<String>(

        // Connect the ListView to our data

        // Check if the FrameLayout with the id details exists
        View detailsFrame = getActivity().findViewById(;

        // Set mDuelPane based on whether you are in the horizontal layout
        // Check if the detailsFrame exists and if it is visible
        mDuelPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

        // If the screen is rotated onSaveInstanceState() below will store the // hero most recently selected. Get the value attached to curChoice and // store it in mCurCheckPosition
        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);

        if (mDuelPane) {
            // CHOICE_MODE_SINGLE allows one item in the ListView to be selected at a time
            // CHOICE_MODE_MULTIPLE allows multiple
            // CHOICE_MODE_NONE is the default and the item won't be highlighted in this case'

            // Send the item selected to showDetails so the right hero info is shown

    // Called every time the screen orientation changes or Android kills an Activity
    // to conserve resources
    // We save the last item selected in the list here and attach it to the key curChoice
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("curChoice", mCurCheckPosition);

    // When a list item is clicked we want to change the hero info
    public void onListItemClick(ListView l, View v, int position, long id) {

    // Shows the hero data
    void showDetails(int index) {

        // The most recently selected hero in the ListView is sent
        mCurCheckPosition = index;

        // Check if we are in horizontal mode and if yes show the ListView and
        // the hero data
        if (mDuelPane) {

            // Make the currently selected item highlighted
            getListView().setItemChecked(index, true);

            // Create an object that represents the current FrameLayout that we will
            // put the hero data in
            DetailsFragment details = (DetailsFragment)

            // When a DetailsFragment is created by calling newInstance the index for the data
            // it is supposed to show is passed to it. If that index hasn't been assigned we must
            // assign it in the if block
            if (details == null || details.getShownIndex() != index) {

                // Make the details fragment and give it the currently selected hero index
                details = DetailsFragment.newInstance(index);

                // Start Fragment transactions
                FragmentTransaction ft = getFragmentManager().beginTransaction();

                // Replace any other Fragment with our new Details Fragment with the right data
                ft.replace(, details);

                // TRANSIT_FRAGMENT_FADE calls for the Fragment to fade away

        } else {
            // Launch a new Activity to show our DetailsFragment
            Intent intent = new Intent();

            // Define the class Activity to call
            intent.setClass(getActivity(), DetailsActivity.class);

            // Pass along the currently selected index assigned to the keyword index
            intent.putExtra("index", index);

            // Call for the Activity to open

package com.newthinktank.derekbanas.fragmentlayout;

public class SuperHeroInfo {
     * Our data, part 1.
    public static final String[] NAMES =
                    "Wonder Woman",
                    "Green Lantern",
                    "Martian Manhunter",
                    "Green Arrow"

     * Our data, part 2.
    public static final String[] HISTORY =
                    "Superman is born Kal-El on the alien planet Krypton. His parents, Jor-El and Lara become aware of Krypton's impending destruction and Jor-El begins constructing a spacecraft that would carry Kal-El to Earth. During Krypton's last moments, Jor-El places young Kal-El in the spacecraft and launches it. Jor-El and Lara die as the spacecraft barely escapes Krypton's fate. The explosion transforms planetary debris into kryptonite, a radioactive substance that is lethal to superpowered (as by Earth's yellow sun) Kryptonians.\n" +
                            "\n" +
                            "The spacecraft lands in the rural United States, where it is found by a passing motorist. Jonathan and Martha Kent adopt Kal-El and name him Clark Kent. As Clark grows up on Earth, he and his adoptive parents discover that he has superhuman powers. The Kents teach Clark to use these powers responsibly to help others and fight crime.\n" +
                            "\n" +
                            "Clark keeps his powers secret in order to protect his family and friends, who might be endangered by his criminal enemies. In order to use his powers to help humanity, Clark creates the alter ego of Superman. A number of elements are added to each identity to keep them distinct enough to prevent the casual observer from matching them. Superman wears a characteristic red and blue costume with a letter \"S\" emblem and a cape. Clark Kent takes to wearing glasses, styling his hair differently, changing his body language, significantly altering his voice, and wearing looser clothing and suits that hide his physique.\n" +
                            "\n" +
                            "Clark Kent moves to Metropolis and takes a job as a reporter at the Daily Planet, where he meets his friends and co-workers, Lois Lane, Jimmy Olsen and Editor Perry White. Superman becomes the subject of frequent headline stories written by Lois, and the two become romantically attracted to each other.",

                    "Bruce Wayne is born to Dr. Thomas Wayne and his wife Martha, two very wealthy and charitable Gotham City socialites. Bruce is brought up in Wayne Manor, and leads a happy and privileged existence until the age of eight, when his parents are killed by a small-time criminal named Joe Chill while on their way home from a movie theater. That night, Bruce Wayne swears an oath to spend his life fighting crime. He engages in intense intellectual and physical training; however, he realizes that these skills alone would not be enough. \"Criminals are a superstitious cowardly lot,\" Wayne remarks, \"so my disguise must be able to strike terror into their hearts. I must be a creature of the night, black, terrible...\" As if responding to his desires, a bat suddenly flies through the window, inspiring Bruce to take on the persona of Batman.",

                    "Diana was a member of a tribe of women named the Amazons, native to Paradise Island â a secluded island set in the middle of a vast ocean. Captain Steve Trevor's plane crashes on the island and he is found alive but unconscious by Diana and a fellow Amazon. Diana has him nursed back to health and falls in love with him. A competition is held amongst all the Amazons by Diana's mother, the Queen of the Amazons Hippolyte, in order to determine who is the most worthy of all the women; Hippolyte charges the winner with the responsibility of delivering Captain Steve Trevor back to man's world and to fight for justice. Hippolyte forbids Diana from entering the competition, but she takes part nonetheless, wearing a mask to conceal her identity. She wins the competition and reveals herself, surprising Hippolyte, who ultimately gives in to Diana's wish to go to Man's World. She then safely returns Steve Trevor back to his home and is awarded a special dress made by her mother for her new role as Wonder Woman.\n" +
                            "\n" +
                            "Coming to America for the first time, Wonder Woman comes upon a weeping army nurse named Diana Prince. Inquiring about her state, she finds that the nurse wanted to leave for South America with her fiancé but was unable to due to shortage of money. As both of them looked identical and Wonder Woman needed a job and a valid identity to look after Steve (who was admitted in the same army hospital), she gives her the money she had earned earlier to help her go to her fiancé in exchange for her credentials. The nurse reveals her name as Diana Prince, and thus, Wonder Woman's secret identity was created, and she began working as a nurse in the army.",

                    "Barry Allen is a police scientist (his job title was changed to a forensic scientist in The Flash: Iron Heights one-shot) with a reputation for being very slow, deliberate, and frequently late, which frustrates his fiancee, Iris West. One night, as he is preparing to leave work, a lightning bolt shatters a case of chemicals and spills them all over Allen. As a result, Allen finds that he can run extremely fast and has matching reflexes. \n" +
                            "He dons a set of red tights sporting a lightning bolt, dubs himself the Flash, (after his childhood comic book hero, Jay Garrick), and becomes Central City's resident costumed crimefighter. Central City University professor Ira West (Iris' adoptive father) designed Allen's costume (reminiscent of the Fawcett Captain Marvel) and the ring which stores it while Allen is in his civilian identity. The ring can eject the compressed clothing when Allen needs it and suck it back in with the aid of a special gas that shrinks the suit. In addition, Allen invented the cosmic treadmill, a device that allowed for precise time travel and was used in many stories. Allen was so well liked that nearly all speedsters that come after him are constantly compared to him.",

                    "Green Lantern is a superhero and an intergalactic police officer in the DC Universe. The weapon he wields is a power ring that translates his ideas into green energy using the strength of his willpower. He is a member of the Green Lantern Corps, an organization created by the Guardians of the Universe that has established thousands of members distributed throughout each space sector. There have been several assigned to the planet Earth in Sector 2814.\n" +
                            "\n" +
                            "Alan Scott was the original Green Lantern of the Golden Age, and a member of the Justice Society of America. Although he is not a member of the Corps, he taps into the same energy using the magical Starheart. Hal Jordan was the first human Corps member, and is known as possibly the greatest of all time because he never gives up under any circumstances. He received his ring from his predecessor the dying alien Abin Sur, and was a founding member of the Justice League of America.",

                    "Aquaman, also known as Arthur Curry and Orin, is a superhero and the ruler of the seas. As the king of Atlantis and other undersea territories, he technically controls most of the planet. His abilities include super-strength, durability, super-speed, staying underwater indefinitely, and telepathy, which he uses to communicate with sea-life. His aquatic nature means he requires water regularly at the risk of dehydration, although he is perfectly capable of staying on land for extended periods. The Aquaman Family also includes his wife Mera and his side-kicks Aqualad and Aquagirl, along with a number of others, fighting together against villains. He is also a founding member of the Justice League of America. Arthur Joseph Curry was his successor after the original died, and had his own adventures for several years, until Orin was resurrected during Blackest Night and reclaimed his title.",

                    "Martian Manhunter, also known as J'onn J'onzz and John Jones, is a superhero from the planet Mars and the last surviving member of his race. A martian holocaust killed his wife and daughter, nearly driving him mad, until he was brought to Earth in an accident caused by scientist Saul Erdel. His natural abilities include super-strength, super-speed, invulnerability, flight, shape-shifting, intangibility and telepathy. He has been a member of almost every incarnation of the Justice League of America. Although he holds great reverence for his homeworld, he has come to greatly respect his adopted world as well and protects it as his home. In his secret identity, to blend into humanity, he is a gritty hard-boiled police officer.",

                    "Green Arrow is a vigilante superhero who fights crime using archery, technology, and martial arts. In his secret identity he is politician and billionaire Oliver Queen, a hot-headed social activist and owner of Queen Industries. Black Canary is his long-time love interest and Speedy is his side-kick. The extended family of heroes who work with him call themselves Team Arrow. Oliver was killed in an explosion at one point and remained dead for many years until he was resurrected during the Quiver storyline. He has been a member of the Justice League and the Outsiders."

4 Responses to “How to Make Android Apps 12”

  1. ironwire says:

    I have to say Derek is a very very smart guy. He have experienced such many fields in each of which he is expert. He has ability to make money and he love to help people. Truly Wonderful person. How much time do you spend one day in making videos and/or doing other works?

    • Derek Banas says:

      Thank you for the nice compliments 🙂 I’m extremely lucky to be able to do what I do. Each video takes about :

      30 minutes for planning
      40 minutes recording / writing code
      50 minutes editing
      4 hours rendering

      It sounds like a lot, but most of the time is taken up rendering which happens over night. It is very fun for me 🙂

  2. Matt says:


    You are great guy and your tutorials helped me a lot.

    However I got one question that bothers me…
    I’m creating app that takes few inputs from EditText, after that on button click it sends data to table that is created dynamically and also do some calculations.

    Everything works perfectly fine and program looks the way I want it to look. One problem that I have and I can’t find answer anywhere to it is how to save this table that’s being created and have it after my screen rotates.

    I know that they are onSave… methods that’s works for stuff that created in your xml file etc. But how to save and restore something that has been created programmatically?

    Thanks for help,

    • Derek Banas says:

      Hi Matt, Thank you for the compliment 🙂 To save changes between screen rotations I normally save data in a bundle. That is the default use for onSaveInstanceState. Otherwise a SQLite database may be useful.

Leave a Reply

Your email address will not be published.