Fragments are used to place two activities on a single activity when creating the layout of the user interface. Fragments can’t exist on their own; they require activity or other fragments. The fragment’s layout, lifecycle, and input events are managed and defined by themselves. The interaction between fragment objects is managed by the fragment manager class.
There are four steps for making fragments.
Extend fragment class
Provide appearance in XML /Java
Override onCreateView to link the appearance
Use the fragment in XML / Java
Example:
activity_main.xml
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
<?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:id="@+id/layout_potrait" android:orientation="horizontal" tools:context=".MainActivity"> <!-- mainactivity--> <fragment android:id="@+id/lis_frag" android:name="com.packagename.fragment.ListFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" tools:layout="@layout/fragment_list" /> <fragment android:id="@+id/fragment2" android:name="com.packagename.fragment.DetailFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" tools:layout="@layout/fragment_detail" /> </LinearLayout>
activitymain2.xml(land_layout)
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
<?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:id="@+id/layout_land" android:orientation="horizontal" tools:context=".MainActivity"> <!--layout_land--> <fragment android:id="@+id/lis_frag" android:name="com.packagename.fragment.ListFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" tools:layout="@layout/fragment_list" /> <fragment android:id="@+id/fragment2" android:name="com.packagename.fragment.DetailFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" tools:layout="@layout/fragment_detail" /> </LinearLayout>
Listfragment
1 2 3 4 5 6 7 8 9 10 11 12 13
<?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=".ListFragment"> <!-- listfragment layout --> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout>
Detail fragment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?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:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimaryDark" android:orientation="vertical" tools:context=".DetailFragment"> <!-- detailfragment--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:layout_marginRight="20dp" android:text="TextView" android:textSize="18sp" android:textStyle="bold" /> </LinearLayout>
MainActivity JavaFile
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
46
47
package com.packagename.fragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements ListFragment.itemse {
TextView textView;
String[] text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
text = getResources()
.getStringArray(R.array.descriptions);
if (findViewById(R.id.layout_potrait) != null) {
//fragmentmanager
FragmentManager manager = this.getSupportFragmentManager();
manager.beginTransaction()
.hide(manager.findFragmentById(R.id.fragment2))
.show(manager.findFragmentById(R.id.lis_frag))
.commit();
}
if (findViewById(R.id.layout_land) != null) {
FragmentManager manager = this.getSupportFragmentManager();
manager.beginTransaction()
.show(manager.findFragmentById(R.id.fragment2))
.show(manager.findFragmentById(R.id.lis_frag))
.commit();
}
}
//method to find id
@Override
public void onItemse(int index) {
textView.setText(text[index]);
if (findViewById(R.id.layout_potrait) != null) {
FragmentManager manager = this.getSupportFragmentManager();
manager.beginTransaction()
.show(manager.findFragmentById(R.id.fragment2))
.hide(manager.findFragmentById(R.id.lis_frag))
.addToBackStack(null)
.commit();
}
}
}
ListFragment 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
46
//package import
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//defining ListFragment class
public class ListFragment extends androidx.fragment.app.ListFragment {
itemse activity; //variable
public interface itemse { //function
void onItemse(int index);
}
public ListFragment() { //function
}
@Override
public void onAttach(@NonNull Context context) { //onattach method
super.onAttach(context);
activity = (itemse) context;
}
//on activity creation
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] data = getResources()
.getStringArray(R.array.pieces);
//data string array
setListAdapter(new ArrayAdapter < String > (getActivity(), android.R.layout.simple_list_item_1, data));
if (this.getActivity()
.findViewById(R.id.layout_land) != null) {
activity.onItemse(0);
}
}
//on list item click
@Override
public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
activity.onItemse(position);
}
}
DetailFragment Java file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.packagename.fragment;
//To import classes
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
// DetailFragment class
public class DetailFragment extends Fragment { //it extends the Fragment class
public DetailFragment() {}
//create onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// to inflate the layout
return inflater.inflate(R.layout.fragment_detail, container, false); //return it
}
}
Output
The fragment is contained inside the activity and links closely to the lifecycle of an activity. The main difference between fragment and activity lifecycles is that activity creates only one view for the entire lifetime but fragment views can be recreated and even dynamically changed during the lifetime.
1. onAttach():- This callback is the first method of the fragment lifecycle. In this state, the fragment attaches to its host activity and is added to FragmentManager. It means that there has been a call to a fragment.
2. onCreate():- This callback is called immediately after creating the activity. Until onCreate() the flow is working on its own. It tries to fetch the fragments and know what things are going on in the background.
3. onCreateView():- This callback is used to create the view; it is basically used to inflate the layout you want in your activity. This method returns a view component. This method has three parameters, LayoutInflater, ViewGroup, and Bundle.
4. OnActivityCreated():- This callback is called after the onCreate() method. This method is actually called after the view has been fully created and it’s ready to be loaded. Then, activities created, functions or methods of the items like findViewById() and other activity parameters are likely to be using your own fragment.
5. onViewsStateRestored():- This callback provides information to the fragment.
6. onStart():- This states activity is ready for user interaction. In this state fragments are visible.
7. onResume():- In this, the fragment becomes active, though it will not be ready for work.
8. onPause():- It occurs when the user is about to leave the fragment. We can save our changes during this time if we want.
9. onStop():- After onStop() the view is destroyed. View destroy means inflated has been removed.
10. onDestoryView():- Fragment view will destroy after calling this method (the view for the fragment will be destroyed).
11. onDestory():- This method is called to do a final clean-up of the fragment’s state but it will not be guaranteed to be called by the Android platform.