In this Android Studio article i want to show you How to Add Fragment at Run time.
so for good explanation you can watch the video for this article at the end .
Also you can read more android development articles
1: Android Development Articles
Also you can check Python GUI Development Tutorials in the below link.
1: PyQt5 GUI Development Tutorials
2: TKinter GUI Development Tutorials
3: Pyside2 GUI Development Tutorials
4: Kivy GUI Development Tutorials
5: wxPython GUI Development Tutorials
What is Fragment ?
A Fragment is a piece of an activity which enable more modular activity design.
A fragment encapsulates functionality so that it is easier to reuse within activities
and layouts.Android devices exists 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 Life cycle
Android fragments have their own life cycle very similar to an android activity.
- onAttach() : The fragment instance is associated with an activity instance.The fragment and the activity is 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 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.
- onActivityCreated() : 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.
So there are two ways that you can create fragments, the first way is that you can add a
fragment to your main activity through xml file, you can check this article for that
How To Add Fragment Through XML. and the second way is that you can add fragment to the
main activity dynamically. in this article we are going to focus on adding fragment dynamically
to our main activity.
1: First of all create a new project in your Android Studio, and choose Empty Activity also iam
using API 20 for this project.
2: Now you need to add a container to your main_activity.xml , because when you want to add a fragment dynamically you need to add a container, i have added a FrameLayout as a container like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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" tools:context=".MainActivity"> <FrameLayout android:id="@+id/container" android:layout_width="368dp" android:layout_height="495dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> </FrameLayout> </android.support.constraint.ConstraintLayout> |
3: After that you need to create two fragments in android studio, basically when you create a fragment there will be two files the first one is the xml file for the fragment and the second one the .java file for the fragment , in fragment the class of java file extends from Fragment. so now this is the code for our two fragments, and we are going to add just a simple TextView with a Button in the fragment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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" tools:context=".FootballFragment" android:background="@color/colorAccent" > <!-- TODO: Update blank fragment layout --> <TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="36dp" android:layout_marginStart="8dp" android:layout_marginTop="52dp" android:layout_marginEnd="8dp" android:text="Football Fragment" android:textAlignment="center" android:textColor="@android:color/white" android:textSize="20sp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnCrick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="28dp" android:layout_marginEnd="8dp" android:text="Open Cricket Fragment" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </android.support.constraint.ConstraintLayout> |
and this is the second fragment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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" tools:context=".FootballFragment" android:background="@color/colorPrimary" > <!-- TODO: Update blank fragment layout --> <TextView android:id="@+id/textView" android:layout_width="0dp" android:layout_height="36dp" android:layout_marginStart="8dp" android:layout_marginTop="52dp" android:layout_marginEnd="8dp" android:text="Cricket Fragment" android:textAlignment="center" android:textColor="@android:color/white" android:textSize="20sp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnFootball" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="28dp" android:layout_marginEnd="8dp" android:text="Open Football Fragment" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </android.support.constraint.ConstraintLayout> |
So now this is the java code for our FootballFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.forogh.parwiz.fragmentdynamically; 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.Button; /** * A simple {@link Fragment} subclass. */ public class FootballFragment extends Fragment { private Button btnOpenCrick; public FootballFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_football, container, false); btnOpenCrick = view.findViewById(R.id.btnCrick); btnOpenCrick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.fragmentManager.beginTransaction().replace(R.id.container, new CricketFragment(), null).addToBackStack(null).commit(); } }); return view; } } |
In this code the important point is the replacing of our fragment in the button click like this.
1 2 3 4 5 6 |
btnOpenCrick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.fragmentManager.beginTransaction().replace(R.id.container, new CricketFragment(), null).addToBackStack(null).commit(); } }); |
And now this is the java code for our CricketFragment.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.forogh.parwiz.fragmentdynamically; 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.Button; /** * A simple {@link Fragment} subclass. */ public class CricketFragment extends Fragment { private Button btnOpenFootball; public CricketFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_cricket, container, false); btnOpenFootball = view.findViewById(R.id.btnFootball); btnOpenFootball.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.fragmentManager.beginTransaction().replace(R.id.container, new FootballFragment(), null).addToBackStack(null).commit(); } }); return view; } } |
Now open open your MainActivity.java and add these codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.forogh.parwiz.fragmentdynamically; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { public static FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); if(findViewById(R.id.container) != null) { if(savedInstanceState != null) { return; } FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); FootballFragment footballFragment = new FootballFragment(); fragmentTransaction.add(R.id.container, footballFragment, null); fragmentTransaction.commit(); } } } |
Run the complete project and this will be the result.
Also you can watch the complete video for this article.
For navigation back check this video
Subscribe and Get Free Video Courses & Articles in your Email