Android program to implement Fragment
In Android, fragment is a part of an activity. Fragment is a GUI component which is inside an activity. A fragment has its own life cycle. Fragments are designed to be reusable UI layouts with logic inside it. The reason we use fragments in android is that, as the mobile market is evolving, there are so many devices with different screen sizes(tablets, mobile, phone + tablets), so in order to provide the best user interface possible, fragments are used. There are a lot more reasons, but this one should be suitable for now.
Fragment lifecycle is similar to that of the Activity lifecycle.
In this program, we will see how to pass data or communicate between fragments.
We will be adding one fragment statically that is adding in xml file and another fragment dynamically that is adding programmatically in the java file and we will pass data between these two fragments so that you are familiar to both ways of using fragments
Steps to create the application:-
- Open Android Studio and create a new Android application and name it as “Fragment” and company domain as codedost so your package will be automatically set.
- Open an Empty Activity and name it as MainActivity.
- Create two more Activites and name it as first and second respectively and also create their respective xml files.
- Copy the contents of res/layout/activity_main.xml , res/layout/first_fragment.xml and res/layout/second_fragment.xml file.
- Run the application to launch Android emulator or you can run it on your mobile also(which is way faster).
XML File(res/layout/activity_main.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context="codedost.fragment.MainActivity"> <fragment android:layout_width="match_parent" android:layout_height="0dp" android:id="@+id/fr1" android:layout_weight="1" android:background="#0f0" android:name="codedost.fragment.first"></fragment> <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@color/colorAccent" android:id="@+id/fr2" android:name="codedost.fragment.second"></FrameLayout> </LinearLayout>
XML File(res/layout/first_fragment.xml):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="#0f0" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:textColorHint="#fff" android:hint="Enter text" android:id="@+id/editext"></EditText> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send" android:layout_below="@+id/editext" android:layout_alignParentStart="true" /> </RelativeLayout>
XML File(res/layout/second_fragment.xml):
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:textSize="27sp" android:hint="You will receive the text here!" android:textColorHint="#fff" android:textColor="#fff" android:gravity="center" android:id="@+id/rtxt"/> </RelativeLayout>
MainActivity.java
package codeodst.fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity implements first.OnFragmentInteractionListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); placeFragmentDynamically(); } private void placeFragmentDynamically(){ FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.add(R.id.fr2,new second()); ft.commit(); } @Override public void onFragmentInteraction(String msg) { second s = (second)getFragmentManager().findFragmentById(R.id.fr2); s.receivedinfo(msg); } }
first.java
package codedost.fragment; import android.content.Context; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class first extends Fragment { EditText mMessage; Button msubmitbtn; private OnFragmentInteractionListener mListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.first_fragment, container, false); mMessage = (EditText) view.findViewById(R.id.editext); msubmitbtn = (Button) view.findViewById(R.id.button1); msubmitbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String mSend = mMessage.getText().toString(); if(mSend.isEmpty()) { Toast.makeText(getContext(),"You have not sent anything",Toast.LENGTH_SHORT).show(); } else onButtonClick(mSend); } }); return view;//return view } public void onButtonClick(String msg) { if(mListener!=null) { mListener.onFragmentInteraction(msg); } } @Override public void onAttach(Context context) { super.onAttach(context); try { mListener=(OnFragmentInteractionListener)context ; } catch (ClassCastException e){ } } public interface OnFragmentInteractionListener { void onFragmentInteraction(String msg); } }
second.java
package codedost.fragment; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class second extends Fragment { private TextView mReceivedmsg; @Override public View onCreateView(LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState) { View view = inflater.inflate(R.layout.second_fragment,container,false); mReceivedmsg= (TextView) view.findViewById(R.id.rtxt); return view; } public void receivedinfo(String txt) { mReceivedmsg.setText(txt); } }
Output