Changes

Jump to: navigation, search

Using Fragments in Android Studio - An Example

2,067 bytes removed, 20:37, 8 May 2014
no edit summary
Before proceeding to the next step, double click on the TextFragment instance in the layout and, within the resulting panel, change the id of the fragment to @+id/text_fragment.
 
----------------------
The main activity for the application has associated with it an XML layout file named activity_fragment_example.xml. For the purposes of this example, the fragments will be added to the activity using the <fragment> element within this file. Using the Project tool window, navigate to the src -> main -> res -> layout section of the FragmentExample project and double click on the activity_fragment_example.xml file to load it into the Android Studio Designer tool. Switch from Design mode to Text mode by clicking on the text tab at the bottom of the Designer panel. Modify the XML to remove the default TextView object, any padding properties and to embed the two fragments as follows:
 
<pre>
<RelativeLayout 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="com.ebookfrenzy.fragmentexample.fragmentexample.FragmentExampleActivity">
 
<fragment
android:id="@+id/toolbar_fragment"
android:name="com.ebookfrenzy.fragmentexample.fragmentexample.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="@layout/toolbar_fragment" />
 
<fragment
android:id="@+id/text_fragment"
android:name="com.ebookfrenzy.fragmentexample.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="@layout/text_fragment" />
 
</RelativeLayout>
</pre>
 
Click on the Design tab to return to the graphical view and note that the fragments are now visible in the layout as demonstrated in Figure 23-4:
 
[[Image:android_studio_embedded_fragments.png|The user interface layout for an Android Studio fragment tutorial]]
 
Figure 23-4
== Making the Toolbar Fragment Talk to the Activity ==
[[Image:android_studio_fragment_example_running.png|An Android Studio fragment example app running]]
Figure 23-58

Navigation menu