Android Fragments UI Design Example

By | March 10, 2014

Android Fragments are the user Interface which represents a part of an activity , in other words you can also say fragments are the sub-part of an activity .

fragment runs in the context of an activity in which it is placed but it has it’s own life which depends on the life cycle of an host activity , i.e when host activity resumes fragment too , when host activity stops fragments too .

Note: Android introduced fragments in Android 3.0 (API level 11) i.e Honeycomb

Fragment Life Cycle Methods

onAttach() :-Here In this Method Fragment instance gets associate with Activity instance.

onCreate() :- Fragment View hierarchy is created .

onCreateView() :- Fragment View hierarchy is created , and this inflated View become part of the view hierarchy of its containing Activity .

onActivityCreated():- Both Activity and Fragment instance has been created and also there view hierarchy .

onResume():- Fragment becomes visible and active .

onPause():- Fragment becomes visible but not active .

onStop():- Fragment becomes Invisible .

Lets See An Example

In this tutorial we will see an example in which we embed two fragments in one activity , one fragment which we name it as list fragment which contains three Buttons and another fragment which we name it as detail fragment which contain one TextView , onclick of any button inside the list fragment we will update the textview inside the detail fragment .

Below is the diagrammatic representation of UI Design .

Landscape Mode

Portrait Mode

 

Project Name FragmentDemo
Package com.pavan.fragmentdemo
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

We are creating following activities and fragments according to device orientation .

LandScape Mode Portrait Mode
Activity Fragments
MainActivity ListFragment
DetailFragment
 Activities Fragments
MainActivity ListFragment
DetailActivity DetailFragment

Fragment XML Layouts

we are defining two xml layouts for fragments inside layout directory of the project

  1. list_fragment.xml
  2. detail_fragment.xml

file : list_fragment.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:background="#CCFF99"
 android:orientation="vertical"
 android:padding="5dp" >
   <Button
      android:id="@+id/android_btn_id"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Android" />

 <Button
    android:id="@+id/ios_btn_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="IOS" />

 <Button
    android:id="@+id/windows_btn_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Windows" />

</LinearLayout>

file : detail_fragment.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:background="#FFFF99"
 android:orientation="vertical"
 android:padding="20dp" >
 
  <TextView
    android:id="@+id/display_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:textSize="40sp" />

</LinearLayout>

Main Activity Layout

file : activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="horizontal" >
  <fragment
    android:id="@+id/list_Fragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    class="com.pavan.fragmentdemo.MyListFragment" >
 </fragment>

 <fragment
   android:id="@+id/detail_Fragment"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="2"
   class="com.pavan.fragmentdemo.DetailFragment" >
 </fragment>

</LinearLayout>

Defining fragments

we have declared two xml fragments layout ( /res/layout/list_fragment.xml and /res/layout/detail_fragment.xml ) above . To define a new fragment we either extend the Fragment class or one of its subclasses, for example, ListFragment , DialogFragment , PreferenceFragment or WebViewFragment

Create Two Classes for above defined xml fragment layout and extend it to Fragment class

  1. DetailFragment.java
  2. ListFragment.java

Note : Inside the Main Activity XML Layout the fragment tag contains an attribute/ property whose values corresponds to the respective fragment class name

file :- DetailFragment.java

package com.pavan.fragmentdemo;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class DetailFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.detail_fragment, container, false);
 return view;
 }

 // we call this method when button from listfragment is clicked
 public void setText(String item) {
 TextView view = (TextView) getView().findViewById(R.id.display_tv);
 view.setText(item);
 }
}

file :- ListFragment.java

package com.pavan.fragmentdemo;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class MyListFragment extends Fragment implements OnClickListener {

 private Communicator communicator;

 Button android_btn, ios_btn, windows_btn;

 @Override
 public void onAttach(Activity activity) {
 super.onAttach(activity);
 if (activity instanceof Communicator) {
 communicator = (Communicator) activity;
 } else {
 throw new ClassCastException(activity.toString()
 + ” must implemenet MyListFragment.Communicator”);
 }
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.list_fragment, container, false);

 // Initialize Views
 android_btn = (Button) view.findViewById(R.id.android_btn_id);
 ios_btn = (Button) view.findViewById(R.id.ios_btn_id);
 windows_btn = (Button) view.findViewById(R.id.windows_btn_id);

 // set on click Listeners for buttons
 android_btn.setOnClickListener(this);
 ios_btn.setOnClickListener(this);
 windows_btn.setOnClickListener(this);

 return view;
 }

//Create Interface 
 public interface Communicator {
 public void Message(String OS_Name);
 }

 @Override
 public void onClick(View v) {
 switch (v.getId()) {
 case R.id.android_btn_id:
 updateFragment(“Android”);
 break;

 case R.id.ios_btn_id:
 updateFragment(“IOS”);
 break;

 case R.id.windows_btn_id:
 updateFragment(“Windows”);
 break;
 }

 }

 private void updateFragment(String OS_Name) {
 communicator.Message(OS_Name);
 }

}

Inter Fragment Communication Via Host Activity

The Communication between fragments doesn’t happen directly , but instead the communication is done via the activity , for that we define an interface inside the fragment class and require the activity which uses it must implement it.

Here in this example we are updating TextView of detailfragment , on click of any Buttons inside listfragment , so the communication is happening from listfragment to detailfragment , so we define the interface for listfragment.

Lets discuss programmatically how the communication takes place.

  • Define Communicator interface inside MyListFragment class.
  • Declare a method Message inside MyListFragment.
  • Implement Communicator Interface for MainActivity class.
  • Override the Message method of Communicator interface inside MainActivity.
  • onclick of button inside listfragment we call Message method via updateFragment.
  • finally we update the detailfragment inside Message method .

Main Activity

file :- MainActivity.java

package com.pavan.fragmentdemo;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity implements
 ListFragment.Communicator {

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

 @Override
 public void Message(String OS_Name) {
 DetailFragment detailfragment = (DetailFragment) getFragmentManager()
 .findFragmentById(R.id.detail_Fragment);
 if (detailfragment != null && detailfragment.isInLayout()) {
 detailfragment.setText(OS_Name);
 }

 }

}

Layout Optimization ( Layout for Portrait Mode )

Create layout-port folder inside res directory of your project and inside this layout-port folder create activity_main.xml file , the android system easy determines the device orientation and fit according to it , so the layout file inside layout-port fits in portrait mode.

file : layout-port/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="vertical" >
    
    <fragment
        android:id="@+id/list_Fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.pavan.fragmentdemo.MyListFragment" >
    </fragment>

</LinearLayout>

Create detail_activity.xml layout file inside the layout folder , this layout is used to show in portrait mode only

file : layout/detail_activity.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" >
     <fragment
       android:id="@+id/detailFragment"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       class="com.pavan.fragmentdemo.DetailFragment" />

</LinearLayout>

Create a DetailActivity and set the content of this activity with the above defined detail_activity.xml layout , and inside the onCreate() method of this class check the orientation of the device and i have written a tutorial on how to Check Android Screen Orientation At Run time if the device is landscape mode then kill the activity by calling finish() and if the activity is in portrait mode set it with detail_activity.xml layout

file : DetailActivity.java

package com.pavan.fragmentdemo;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;

public class DetailActivity extends Activity {

 public static String os_name = “”;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
 finish();
 return;
 }
 setContentView(R.layout.detail_activity);
 Bundle extras = getIntent().getExtras();
 if (extras != null) {
 String name = extras.getString(os_name);
 DetailFragment detailFragment = (DetailFragment) getFragmentManager()
 .findFragmentById(R.id.detailFragment);
 detailFragment.setText(name);
 }

 }

}

finally inside the message(String ) of main activity check if the layout contains the detail_fragment.xml layout if not then create intent and start DetailActivity .

public void Message(String OS_Name) {
 DetailFragment detailfragment = 
  (DetailFragment) getFragmentManager()
   .findFragmentById(R.id.detail_Fragment);
 
if (detailfragment != null && detailfragment.isInLayout()) {
     detailfragment.setText(OS_Name);
 } else {
    Intent intent = new Intent(getApplicationContext(),
    DetailActivity.class);
    Bundle extras = new Bundle();
    extras.putString(DetailActivity.os_name, OS_Name);
    intent.putExtras(extras);
    startActivity(intent);
 }

 }

RUN

Portrait
Android Fragment Multi pan UI For portrait Android Fragment Multi pan UI For portrait
Landscape
Android Fragment Multi pan UI For landscape Android Fragment Multi pan UI For Landscape
  • Anonymous

    thanks.. I Hope u can make more and more good tutorials like this.And expecting

  • Hi Your blog is very nice,very easy to understand and nice way of explanation.
    I have a doubt,activity with fixed button,when i swipe layout button is fixed and the layout is slide how ca n i do please help me.with bottom slide indecators.

  • @Kotta Harsha
    for sliding use android navigation drawer
    you can check this article for more
    ( http://www.tutorialsbuzz.com/2014/03/android-sliding-menu-navigation-drawer.html)

  • Correction
    android:textSize="40dp"
    Correct android:textSize="40sp"
    use sp not dp
    http://stackoverflow.com/questions/7107920/why-should-we-use-sp-for-font-sizes-in-android

  • @Mirza Adil

    Thank you for the suggestion i have updated the code 🙂

  • Hey your blog is so interesting and very easy to understand a lot of inspiration in your blog
    thanks for sharing this…!!!

    Try this awesome android game for kids…kids love this type of game..

    https://play.google.com/store/apps/details?id=com.gameimax.kidsshopping

  • Check this amazing android game blog for kids..a lot of fun in this game..

    https://play.google.com/store/apps/details?id=com.gameimax.funrescue

  • Hey your blog is very useful for me but i am little bit confused in my app.
    As i want to move from one activity to another.As i have listed multiple buttons in List-Fragment and i want to display another activity in detail-Fragment.Can you plz help me for the same?

  • @Runali
    Use the concept of Inter fragment communication which u can find in the article above
    Soon i will be posting more tutorials on listfragment in future blog post

  • Hi Pavan Deshpande ,
    Good work .

  • NIce blog yar… Very easy to understand…

  • Buddy, awesome work 🙂

  • when clicking on buttons it shows text in other fragments. i want to show images also with text while clicking on buttons. is that possible ? if it's plz help me how can i do that ? where should i have make changes in code ?

  • congratulations on the blog.
    The code with this error for me. in the line
    "communicator (OnItemSelectedListener) activity;"
    Help. Thank you

  • congratulations on the blog.
    The code with this error for me. in the line
    "communicator (OnItemSelectedListener) activity;"
    Help. Thank you

  • i am not able to get the portrait view properly
    on clicking buttons in the view then app stops working
    how to display txt in next fragment…pls help..its urgent

  • @Sumanth Ramesh
    You Need To Rotate the Device to see the change in UI In Portrait and Landscape Mode

  • casting to MainAcitivy (who host the fragment)
    communicator = (MainActivity) activity;

  • How about using fragment with back stack, can you please have a tutorial for it?
    I am a college student and our thesis is an android app, we need some tutorials using fragments and actually using database. I am hoping and very grateful if you can help us. Anyway, Thanks for this tutorial 🙂

  • @Aiza

    Sure I Will Write On it

  • i want to implement above fragment in tab layout. is it possible? how?

  • I have this error message when i run on portrait mode. anyone can help. i'm beginner for android dep.
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.fragmentdemo/com.example.fragmentdemo.DetailActivity}; have you declared this activity in your AndroidManifest.xml?

  • hello Pavan
    very good example.
    how can i use gridview(images) instead of listview?
    and Full screen image fragment instead of DetailFragment?
    help me please

  • hello,
    very good example.
    how can i use gridview(images) instead of listview?
    and Full screen image fragment instead of DetailFragment?
    help me please

  • can you send me source code of this ?
    i don't know why i can run this ! please help me

  • While running this code I am getting following error. Please help to resolve this.

    java.lang.RuntimeException: Unable to start activity componentInfo: android.view.InflateException:Binary XML file line #8: Error Inflating class fragment

  • the code I am not able to download can you please send me the code.

  • Great tutorial..MANY THANKS.