ZOFTINO.COM android and web dev tutorials

Android Fragments Implementation

In your app, there could be certain screens on which only part of information needs to be updated on certain events. Or, to provide good user experience, you may want to display extra information on large screen devices whereas the same information is displayed on multiple screens on the small screen devices.

Android provides Fragments to handle these scenarios. Fragments are reusable modules of a screen and an activity. Fragment has its own call back methods, defines its own UI layout and handles UI events.

In android, each app screen is associated with an activity. Fragment represents part of UI. Activity contains Fragments to provide complete UI.

android fragments example

Fragment lifecycle methods

Like activity is created by extending Activity class, fragment is created by extending Fragment class and its subclasses DialogFragment, ListFragment and PreferenceFragment etc. Similar to activity call back methods, fragment has call back methods too.

Important call back methods are onAttach, Oncreate and onCreateView. System calls onAttach method when fragment has been attached to activity. Oncreate method is called when fragment is created. Method onCreateView is called to get UI and it returns view.

Steps to Implement Fragments

  • Create a fragment class which is a subclass of Fragment
  • Implement required call back methods and input handling methods
  • Define UI layout for fragment in xml
  • Implement onCreateView() call back method of fragment class to provide fragment user interface defined in xml
  • Add fragment to activity, you can add fragment in activity layout xml file or runtime using fragment transaction manager

Fragments example

Example app code is shown below. It has three screens. Main screen displays list of stores. On clicking a store it takes user to coupons screen. Coupons screen consists of two fragments. One fragment lists all coupons for the selected store. Second fragment shows coupon details of the selected coupon from the first fragment.

User interface is not defined in xml file for both fragments (list and details fragments) because first fragment is a ListFragment and layout is set using method setListAdapter. Array of data is passed to setListAdapter method to show list of items.

Second fragment’s ,details fragment, layout is defined in onCreateView method of the fragment. This fragment is added to activity layout from list fragment.

On clicking an item in list fragment, list fragment’s onListItemClick method gets called. This method passes the index to details fragment and replaces the details fragment to show details of the selected item in the details fragment.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zoftino.fragments">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".CouponsActivity">

        </activity>
    </application>

</manifest>

MainActivity.java

package com.zoftino.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

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

        ArrayAdapter<string> storesAdapter =
                new ArrayAdapter<string>(this, android.R.layout.simple_list_item_1, CouponsData.arrayOfStores);

        ListView listView = (ListView) findViewById(R.id.lv_stores);
        listView.setAdapter(storesAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long id) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, CouponsActivity.class);
                intent.putExtra("ID", id);
                startActivity(intent);
            }
        });

    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.zoftino.fragments.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="List of Stores"
    android:id="@+id/lb_stores" ></TextView>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/lb_stores"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_marginRight="40dp"
    android:layout_marginEnd="20dp"
    android:layout_marginTop="40dp">

    <ListView
        android:id="@+id/lv_stores"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
</LinearLayout>
</RelativeLayout>

CoupsonActivity.java

package com.zoftino.fragments;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;


public class CouponsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.coupons_view);
    }
}

coupons_view.xml

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

    <FrameLayout android:id="@+id/cpnDetails" android:layout_weight="1"
        android:layout_width="0dp" android:layout_height="match_parent"
        android:background="?android:attr/detailsElementBackground"></FrameLayout>

</LinearLayout>

List fragment java

package com.zoftino.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CouponsListFragment extends ListFragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setListAdapter(new ArrayAdapter<string>(getActivity(),
                android.R.layout.simple_list_item_activated_1, CouponsData.arrayOfCoupons));

        getCouponDetails(0);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        getCouponDetails(position);
    }

    public void getCouponDetails(int index){
        CouponDetailsFragment cpnDetails = CouponDetailsFragment.newInstance(index);

        FragmentTransaction ft = getFragmentManager().beginTransaction();

        ft.replace(R.id.cpnDetails, cpnDetails);

        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
    }

}

Details fragment java

package com.zoftino.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

public class CouponDetailsFragment extends Fragment {

    public static CouponDetailsFragment newInstance(int cpnIndex) {
        CouponDetailsFragment cdf = new CouponDetailsFragment();

        Bundle args = new Bundle();
        args.putInt("cpnIndex", cpnIndex);
        cdf.setArguments(args);

        return cdf;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        if(getArguments() != null) {
            text.setText(CouponsData.arrayOfCouponDetails.get(getArguments().getInt("cpnIndex", 0)));
        }else{
            text.setText(CouponsData.arrayOfCouponDetails.get(0));
        }
        scroller.addView(text);
        return scroller;
    }
}