Fragment is sort of like a “sub Activity” that you can reuse in different activities.
Each fragment should be designed as a modular and reusable activity component because each fragment defines:
The fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments.
When you add a fragment in an activity, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by:
However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
You can combine multiple fragments in a single activity to build a multi-pane UI.
A modular fragment allows you to change your fragment combinations for different screen sizes.
See also: responsive design
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as:
See guide/components/fragments.html
To provide a layout for a fragment, you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.
See guide/components/fragments.html
for the background, where you can keep up any:
public class NonUIFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true); // Must be set to true
}
@Override
public View onCreateView(...) {
return null; // You need to return null
}
}
MyFragment myfr = (myFragment) getSupportManager().findFragmentById(R.id.fragment_id);
MyFragment myfr = (myFragment) getSupportManager().findFragmentByTag("TheBeautifulTag");