How to implement Fragments in Android.
A fragment is a part or portion of Activity. It is also known as sub-activity.
The Primary classes related to fragment are:
- android.app.Fragment: Base class for fragment definitions.
- android.app.FragmentManager: Class for interacting with fragments within the activity.
- android.app.FragmentTransaction: Class for performing operations like adding or replacing the fragments.
Google also provides compatibility support v4 package for Fragments.Its main classes are :
- android.support.v4.app.FragmentActivity: The base class for all activity to containing fragment related features.
- android.support.v4.app.Fragment: The base class for all fragment operations.
- android.support.v4.app.FragmentManager: The class for interacting with fragments in activity.
- android.support.v4.app.FragmentTransaction: The class for performing fragments operations like adding,replacing the fragment.
Note: To use compatibility support v4 package your activity must use FragmentActivity as a Base Class.
if you are already familiar with fragments check Android Working with Fragments Part Two
Main Features of Fragment:-
- A Fragment has its own layout and lifecycle similar to Activity.
- A Fragment can be added or removed at runtime thus making UI look appropriate.
- There can many fragments in one activity.
- Fragment are reusable, Fragments must be embedded in activities.
So, Let’s by taking an example:
Steps:-
- Layout for fragment named as data_fragment.
- Create a Fragment named as DataFragment using above layout.
- Layout for fragment named as list_fragment.
- Create a Fragment named as Listing Fragment using above layout.
- Now create a layout for Activity named as activity_main containing above two Fragments we created.
- Now Create an Activity named as MainActivity and run the Project.
Open AndroidStudio or Eclipse and create an android application project and follow the instructions and then click on finish.
- First of all, we will create a layout for fragment as data_fragment
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:background="#5ba4e5" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:textColor="#ffffff" android:layout_gravity="center" android:id="@+id/mainitems"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textColor="#ffffff" android:textSize="30px" android:id="@+id/subitems"/> </LinearLayout>
2. Create Fragment class DataFragment
package com.coderzpassion.fragmentssample; 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.TextView; /** * Created by coderzpassion on 13/06/16. */ public class DataFragment extends Fragment { TextView text,vers; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.data_fragment, container, false); text= (TextView) view.findViewById(R.id.mainitems); vers= (TextView)view.findViewById(R.id.subitems); return view; } public void change(String txt, String txt1){ text.setText(txt); vers.setText(txt1); } }
3. Create a layout named as list_fragment
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listfragment" /> </LinearLayout>
4. Create a Fragment named as ListingFragment
package com.coderzpassion.fragmentssample; 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.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Created by coderzpassion on 13/06/16. */ public class ListingFragment extends Fragment implements AdapterView.OnItemClickListener{ String[] MainItems = new String[] { "main item 1","main item 2","main item 3","main item 4","main item 5","main item 6","main item 7","main item 8","main item 9" }; String[] SubItems = new String[]{"sub item 1","sub item 2","sub item 3","sub item 4","sub item 5","sub item 6","sub item 7","sub item 8","sub item 9"}; ListView list; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view =inflater.inflate(R.layout.list_fragment, container, false); list=(ListView)view.findViewById(R.id.listfragment); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, MainItems); list.setAdapter(adapter); list.setOnItemClickListener(this); return view; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DataFragment txt = (DataFragment)getFragmentManager().findFragmentById(R.id.fragment2); txt.change(MainItems[position], "SubItems : " + SubItems[position]); } }
5. Create a layout named as activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:weightSum="2" > <fragment android:layout_height="match_parent" android:layout_width="0dp" android:layout_weight="1" class="com.coderzpassion.fragmentssample.ListingFragment" android:id="@+id/fragment"/> <fragment android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" class="com.coderzpassion.fragmentssample.DataFragment" android:id="@+id/fragment2"/> </LinearLayout>
6. Create an Activity class named as default MainActivity.
package com.coderzpassion.fragmentssample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Now run this Project you will find the Output like this