Fragment is ui component that can live in an activity. A fragment is not a view by itself. instead, it has view inside. Because it is not a view, the process of adding fragment to activity is different. A fragment is added to ViewGroup inside an activity. The Fragments view is displayed this ViewGroup.
Below are the steps to create Fragments
- Create a Fragment Class
- Create a Fragment Layout XML
The subclassed Fragment class needs to override the onCreateView method inherited from the Fragment class.
The onCreateView gets the LayoutInflator, ViewGroup and Bundle as parameters
import android.app.Fragment;
public class TestFragment extends Fragment
{
@override
public View onCreateView(LayoutInflator inflator, ViewGroup group, Bundle savedInstanceS)
{
View rootView = inflator.inflate(R.layout.test_fragment,group,false);
return rootView;
}
}
Below is the code to add Fragment to the activity
public class TestActivity extends Activity
{
@override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
if(savedInstance == null)
{
getFragmentManager()
.beginTransaction()
.add(R.id.fragmentParentViewGroup,new TestFragment())
.commit();
}
}
}
The fragment is created inside the if statement. Unlike other View components, Activity remembers that what fragments were added to the Activity. Therefore we should add the fragment only once to the Activity.
References:
No comments:
Post a Comment