Android Development 16

Android Fragments TutorialWelcome to part 16 of my Android Development Tutorial, or maybe I should call this one an Android Fragments Tutorial!

There has been a ton of demand for an Android fragments tutorial, so I wanted to try and do it right. It is very easy to get confused by fragments if they aren’t presented in the right way. I did my best to cover a lot in this video and most importantly to keep it simple. If you understand fragments you’ll be able to make great interfaces. Don’t worry I’ll cover everything in future tutorials.

If you like videos like this, it helps to tell Google+ by clicking here

Code from the Video

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SimpleFragment</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello Fragments!</string>
    <string name="main_textview">Main Activity Text View</string>

</resources>

dimens.xml

<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="component_padding">5dp</dimen>

</resources>

fragment_textview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >

   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello_world" />

</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal" >

   <TextView
       android:layout_width="0px"
       android:layout_height="match_parent"
       android:layout_weight="2"
       android:background="#FFF8DC"
       android:padding="@dimen/component_padding"
       android:text="@string/main_textview" />

   <LinearLayout
       android:id="@+id/simplefragment"
       android:layout_width="0px"
       android:layout_height="match_parent"
       android:layout_weight="2"
       android:orientation="vertical"
       android:padding="@dimen/component_padding" />

</LinearLayout>

SimpleFragment.java

package com.newthinktank.simplefragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

// A Fragment is sort of a mini Activity which you can add
// or remove from another Activity.

// You can use them to create reusable pieces you can add 
// to your interface.

// They are often used so that depending on your screen size 
// you can add more or less fragments

public class SimpleFragment extends Fragment {

	// onCreateView is called when the Fragment is first called for
	
	// The LayoutInflater inflates an xml file into the view
	
	// A ViewGroup is an abstract class that all ViewGroups like 
	// LinearLayout extends
	
	// A Bundle is used to pass data between Activities such as
	// variable data you'd want saved if the orientation of the
	// device changes

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

		// Inflate the Fragment, but don't attach it to the main 
		// activity LinearLayout because attachToRoot is marked
		// as false
		
		View simpleFragmentView = inflater.inflate(R.layout.fragment_textview, container, false);

		return simpleFragmentView;
	}

}

MainActivity.java

package com.newthinktank.simplefragment;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.FragmentManager;


public class MainActivity extends Activity {

	// The Fragment that will be added to the main Activity
	
	SimpleFragment simpleFragment;

	// Called when Activity is created

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// The FragmentManager provides methods for interacting
		// with Fragments in this Activity
		
		FragmentManager fragmentManager = getFragmentManager();
		
		// The FragmentTransaction adds, removes, replaces and 
		// defines animations for Fragments
		
		// beginTransaction() is used to begin any edits of Fragments
		
		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

		// Create our Fragment object
		
		SimpleFragment simpleFragment = new SimpleFragment();
		
		// Add the Fragment to the Activity
		
		fragmentTransaction.add(R.id.simplefragment, simpleFragment);
		
		// Schedules for the addition of the Fragment to occur
		
		fragmentTransaction.commit();

	}

}

30 Responses to “Android Development 16”

  1. Chris says:

    Hey Derek,

    This doesn’t have anything to do with the video, but have you used Android Studio yet? And if so how do you like it? Do you think it’s well off to use instead of Eclipse? Also I’m sure you hear this enough but fantastic job on the videos.

    • Derek Banas says:

      Hey Chris, Yes I have used Android Studio and I found it to be pretty much exactly the same as if I used Eclipse. They are nearly identical. I had to install it in a bunch of computer labs and found it was harder to install on some systems. That is why I continue to use Eclipse

      • Matas says:

        Hi,
        not that I dissagree, but I found Android Studio so much superior to Eclipse in regard to develloping Android apps. Yes they both are great IDEs and they both are great for coding Java. And since AS essentialy is IntelliJ (powerful IDE for Java aswell) with a plugin from Google. That makes it very powerful Android IDE too. Again, not that I suggest you to switch from Eclipseto AS (I can see that you know your way very well around it and you should stick with tool that you master) but I would realy like you to embrace it and perhaps even make a video about it 🙂
        I would bet my bottom dollar that you will find many differences and cool tools that Eclipse doesn’t provide.
        Cheers! 🙂
        I found your channel on Youtube only yesturday… VERY professional tutorials many – very useful – thanx for that!

        • Derek Banas says:

          Hi,

          Yes I agree that Android Studio looks nice. I try it out at least once a month. The only real problem I have with it is that I can’t get it to easily install on every OS, which is a requirement that I have because people all over the world watch my videos.

          A local university has me test install it in a few computer labs every month. As soon as it installs as easily as Eclipse Indigo I will definitely use it.

          Thank you for the input and the nice compliments 🙂

          Derek

  2. Y says:

    I tried to follow it word by word and letter by better for the code, but still have the error message “unfortunately simple fragment has stopped”. in LogCat, it shows

    08-07 16:19:17.318: E/AndroidRuntime(7111): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.newthinktank.simplefragment/com.newthinktank.simplefragment.MainActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup

    Any suggestions?

    Thanks,

  3. William L says:

    I have a request: Could you puh-lease make a quiz/exam app tutorial with multiple choice answers and a grading system based on percentage? Also, instead of typing in the code (because we can copy-paste that) you go over the mechanics of the thing with emphasis on Java – which is insane and probably unhealthy 🙂

  4. Konstantinos says:

    Hey Derek…I have a request for you! Wanna be our project manager? The project, an android app and/or rich web app, shall be called “banasoverflow”. Since you overflow us with knowledge, and “us = thousands”, we shall implement a product that resembles the stackoverflow.com website….just for fun and practice….a Banas-community based project 🙂

    • Derek Banas says:

      That’s funny 🙂 Those guys on StackOverflow can be quite vicious. I don’t think I want to mess with them.

      • James says:

        I can’t tell you how much I appreciate this comment… I’ve thought this on many occasions before. Asking questions on stackoverflow can be emotionally damaging. You either ask a question that’s beneath them to answer and get all kinds of crap, or you ask a question they can’t figure out the answer to and get no reply. 😛

  5. al says:

    How did you create the simplefragment.java under the mainactivity.java

  6. Jango says:

    Hello Derek, nice work u are doing here. Thanks for your time and dedication. Please i need you to help me with a bug in ma code,regarding fragments, if i try running the code i get an exception “android.view.InflagteException: Binary xml file line #8 error inflating class fragment” i tried all i could but could not get it fixed.

  7. pAcIfIrE says:

    Dude i did the same code as yours. My LogCat throws ClassCastException. It says android.widget.TextView cannot be cast to android.view.ViewGroup.

    Thanks in advance…..

  8. Anonymous says:

    the fragment_textview.xml is a Linear Layout that has a text view.
    but i didn’t understand why when we created the activity_main.xml, we created a Linear Layout inside of the initial Linear Layout. is that because the second Linear Layout represents the Linear Layout of the fragment xml file.

    if that’s the case
    when we want to create a fragment as relative layout persay, in the main xml(which is a linear layout) we have to create inside a relative layout???

    i’m sorry if my question is not clear

  9. Safouane says:

    i didn’t understand why we created a linear layout inside of the linear layout in the activity_main.xml file!!

    is that because the second linear layout represent the layout of the fragment_textview.xml file (which is a linear layout)

    if that’s true
    if we want a fragment with a relative layout persay
    in the main xml file(lets say it is a linear layout) we have to create a linear layout and inside him we have to creat a relative layout that represents the fragment???

    i’m sorry if my question is not clear..

  10. Marcel.Hofgesang says:

    Hi,

    i tried to insert it to my code, but it doesn’t work 🙁 There is no Error, but when i am running my app the fragment wont appear…

Leave a Reply

Your email address will not be published.

Google+