Sponsor

Introduction To fragment and Fragment Life Cycle With Example by SoftwareTechIT | Example Of Fragment in android | Android Studio Tutorial

    Introduction To fragment and Fragment Life Cycle With Example
in SoftwareTechIT Blog | YouTube Channel 





Welcome to My Blog...  In this Blog, we will Learn Fragment and The Fragment Life cycle and also learn the example of the fragment ok let's start 

  1. Introduction of Fragment 
  2. Life cycle and life cycle methods of fragment 
  3. Types of Fragment 
  4. How to use and steps of fragment
  5. Create fragment and code of fragment

1) Introduction of Fragment



The fragment is a sub-activity or the Fragment is a piece of an activity that enables more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts.
Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layout for landscape and portrait orientation on a smartphone.
The below image shows how two UI modules defined by fragments can be combined into one activity for a tablet design but separated for a handset design.
      





Fragment Diagram

#8 Introduction To Fragment in Android App | Android Tutorial | #SoftwareTechIT


2) Life cycle and life cycle methods of fragment 

  • onAttach() : The fragment instance is associated with an activity instance.The fragment and the activity are not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.
  • onCreate() : The system calls this method when creating the fragment. You should initialize the essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
  • onCreateView() : The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.
  • inactivity created() : The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context object
  • onStart() : The onStart() method is called once the fragment gets visible.
  • onResume() : Fragment becomes active.
  • onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.
  • onStop() : Fragment going to be stopped by calling onStop()
  • onDestroyView() : Fragment view will destroy after call this method
  • onDestroy() :called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform


3) Types of Fragments

  • Single frame fragments : Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view.
  • List fragments : fragments having special list view is called as list fragment
  • Fragments transaction : Using with fragment transaction. we can move one fragment to another fragment.
Handling the Fragment Lifecycle
A Fragment exist in three states :
  • Resumed : The fragment is visible in the running activity.
  • Paused : Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn’t cover the entire screen).
  • Stopped : The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

4) How to use and steps of fragment


Fragment is use in the activity and today we will learn that to create and add fragment 
into the activity ok let's start


Now we will create a fragment using the fragment tag in activity_main.xml file 

then we will create the fragment from go to resource(res) folder in project manager 


Steps to create the android fragment 



  1. start android studio and create the new project 
  2. into activity_main.xml  add fragment tag and two buttons 
  3. then create the blank fragment goto > res > layout > right click and click new > fragment >blank fragment 
  4. then delete all code that is not important live the onCreateView() method in fragment one and fragment two 
  5. then goto activity_main.xml and add the name property in fragment tag and link the fragments 
  6. goto  Main_Activity.java  and  write the code to action perform on button to change the fragment one to fragment two
  7. Now Project is ready 
  8. view the output 

code is below :-


5) Create fragment and code of fragment


Create the project and add two buttons and the fragment in the activity_main.xml

                      
            Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Frag 1" />
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Frag 2" />
    <fragment
        android:id="@+id/f1"
        android:name="com.example.demofragment.Fragment1"
        android:layout_width="match_parent"
        android:layout_height="592dp" />
    <fragment
        android:id="@+id/f2"
        android:name="com.example.demofragment.Fragment2"
        android:layout_width="match_parent"
        android:layout_height="592dp" />
</LinearLayout>


                       Main_Activity.java

public class MainActivity extends AppCompatActivity {
  Button b1,b2;
  Fragment fragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b1=findViewById(R.id.button);
        b2=findViewById(R.id.button2);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               fragment= new Fragment1();
                FragmentManager fm=getSupportFragmentManager();
                FragmentTransaction ft=fm.beginTransaction();
                ft.replace(R.id.f1,fragment);
                ft.commit();


            }
        });
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               fragment=new Fragment2();
                FragmentManager fm=getSupportFragmentManager();
                FragmentTransaction ft=fm.beginTransaction();
                ft.replace(R.id.f1,fragment);
                ft.commit();


            }
        });



    }
}



Fragment1.java






public class Fragment1 extends Fragment {





    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_fragment1, container, false);

    }



}







Fragment2.java






public class Fragment2 extends Fragment {





    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_fragment2, container, false);

    }



}

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".Fragment1">
    <TextView
        android:text="This Is \nFrag 1"
        android:textSize="30dp"
        android:gravity="center"
        android:textColor="#F70000"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".Fragment2">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="This is \nFrag 2"
        android:textSize="30dp"
        android:textColor="#043BF7"
        android:gravity="center"
        />

</FrameLayout>






Post a Comment

0 Comments