× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Adding an Android Fragment to an Activity

Victor Igbokwe
Nov 26, 2015
<p>You build Android apps right?</p> <p>Ever wanted to add a "sub component" within your Android application, more like a customized component that did your every bidding but whose code didn't litter about your fragment? Well say no more, Android Fragments are here to the rescue.</p> <p>Android Fragments are like every other android component, but can have their own context, state and components, even have their own backing layout XML like activities.</p> <p>You create one by extending the Fragment class like so:</p> <pre><code class="language-java">public class CustomFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { } }</code></pre> <p>You override the onCreateView method to restore state and perform similar logic like is done in activities.</p> <p>Here's an example of how to add the fragment from within your activity:</p> <pre><code class="language-java">CustomFragment customFrag = new CustomFragment(); getFragmentManager().beginTransaction().add(android.R.id.custom_content, customFrag).commit();</code></pre> <p>An activity uses the FragmentTransaction class accessible when calling the getFragmentManager() method.</p> <p>android.R.id.custom_content represents the container in which you want your fragment to show.</p> <p> </p> <p>Any further usage of fragments is beyond the scope of this tip, but here's a good resource for getting up to speed with creating fragments.</p> <p><a href="http://developer.android.com/training/basics/fragments/index.html">http://developer.android.com/training/basics/fragments/index.html</a></p>
comments powered by Disqus