Open main menu

CDOT Wiki β

Changes

MAP524/DPS924 Lecture 4

74 bytes removed, 18:03, 18 July 2015
Implementing your own
Were introduced with 3.0 and made things much more complicated. But if you're developing for phones and tablets they actually make things easier.
 
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.
* 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:
<presource lang="java">FragmentManager manager = getFragmentManager();</presource>
* Next get a reference to a fragment transaction like this :
<presource lang="java">FragmentTransaction transaction = manager.beginTransaction();</presource>
* Now create two new fragment objects by instantiating your two fragment classes like this
<presource lang="java">FragmentOne fragOne = new FragmentOne();FragmentTwo fragTwo = new FragmentTwo();</presource>
* Add the two fragments to your transaction like this:
<presource lang="java">transaction.add(R.id.fragView, fragOne, "Fragment1");transaction.add(R.id.fragView, fragTwo, "Fragment2");</presource>
* Now commit your transactions like this:
<presource lang="java">transaction.commit();</presource>
* 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".