Open main menu

CDOT Wiki β

Changes

MAP524/DPS924 Lecture 4

2,501 bytes added, 21:42, 12 July 2015
Fragments
Sometimes (like with the date picker) you'll have a hard time to avoid using a fragment, but almost always you can avoid writing your own fragment if you want to.
 
The [http://developer.android.com/guide/components/fragments.html Android Developer overview] of fragments is expansive but it's a good place to start if you intend to use one.
 
== Implementing your own ==
 
Follow these steps to make a simple app with fragments:
 
* Create a default app named FragmentExample. Set your Minimum SDK to API 15 and choose a Blank activity.
* Add two new Java classes that extend Fragment, each with their own layouts. This is easy to do with Android Studio by selecting New -> Blank Fragment. Name the classes FragmentOne and FragmentTwo. Do not include fragment factory methods or interface callbacks and set the layout names to fragment_one and fragment_two.
* Inside your activity_main.xml layout, insert a LinearLayout group view after the TextView. Make the ID of the LinearLayout "fragView".
* Now in your MainActivity.java class, onCreate method, you'll need to get a reference to the activity fragment manager like this:
<pre>FragmentManager manager = getFragmentManager();</pre>
* Next get a reference to a fragment transaction like this :
<pre>FragmentTransaction transaction = manager.beginTransaction();</pre>
* Now create two new fragment objects by instantiating your two fragment classes like this
<pre>FragmentOne fragOne = new FragmentOne();
FragmentTwo fragTwo = new FragmentTwo();</pre>
* Add the two fragments to your transaction like this:
<pre>transaction.add(R.id.fragView, fragOne, "Fragment1");
transaction.add(R.id.fragView, fragTwo, "Fragment2");</pre>
* Now commit your transactions like this:
<pre>transaction.commit();</pre>
* The code above is strange even for the Android programming world, but that's the way it is. You could also add fragments via XML but that won't give you as much flexibility (which is what you're going for if you're using fragments).
* Modify the two fragment layout files so that each TextView contains a unique string - for example "hello From Fragment One" and "Hello From Fragment Two".
* Also, change the background colours of the two fragments so they can be easily identified - for example "#550000" and "#005500" which are red and green. You can also change the background of the main activity to blue "#000055".
* You can now run your app. However you'll notice that fragment one is sitting on top of fragment two so fragment two is not visible.
* In your activity_main.xml file, change the height of the LinearLayout view group to wrap_content and run your app again. Now it should show both fragments.