Android Fragments: Difference between revisions
Jump to navigation
Jump to search
Line 8: | Line 8: | ||
*Place the Fragment inside an Activity | *Place the Fragment inside an Activity | ||
==Create a subclass of fragment== | ==Create a subclass of fragment== | ||
We create a subclass of Fragment and override the onCreateView to link the layout with the view. | |||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class HelloFragment extends Fragment { | public class HelloFragment extends Fragment { | ||
Line 45: | Line 46: | ||
.... | .... | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Create layout== | ==Create layout== | ||
<syntaxhighlight lang="xml"> | <syntaxhighlight lang="xml"> |
Revision as of 03:02, 23 December 2020
Introduction
Introduced in API 11. They are a small piece of UI and must have an Activity. Fragments can be added or removed from the Activity. They allow you to capture the UI functionality where you may need to share it across different activities. If we look at phone vs tablet we might this it more appropriate to use to activities but the UI code will remain the same.
Creating Layout
- Create a subclass of fragment
- Create layout
- Link layout with Fragment
- Place the Fragment inside an Activity
Create a subclass of fragment
We create a subclass of Fragment and override the onCreateView to link the layout with the view.
public class HelloFragment extends Fragment {
private static final String TAG = HelloFragment.class.getSimpleName();
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(TAG, "onCreateView");
return inflater.inflate(R.layout.fragment_hello, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.i(TAG, "onStart");
}
@Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume");
}
....
Create layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Hello From Fragment"
android:textColor="@android:color/black"/>
</LinearLayout>
Link layout with Fragment
Place the Fragment inside an Activity
Fragment Manager
We use a Fragment manager to manager the fragments transaction which are methods which add, remove or replace fragments for an activity.