Monday, August 3, 2015

Fun with Fragments

For our simple application (2 activities), we are going to use fragments to allow a tablet to see both the list of things (to the left) and the selected thing (to the right): http://developer.android.com/training/basics/fragments/index.html.

The first step will be to create a fragment for ThingActivity and move its functionality into it.  Using Android Studio's New Fragment > Blank wizard we create ThingFragment.

Will start with ThingFragment as it is fairly easy; only displays the id with no interactivity.  The end result consisted of:

note: Because creating the fragment was pretty much from the tutorial (above), opted to simply summarize the actions here.  Going forward, thinking I will use GIT more effectively to show differences.
  • Creating fragment_thing.xml
    • Changing the provided TextView to have id name.
  • Creating ThingFragment.java
    • Only need to override onCreateView to use the fragment_thing.xml.
    • Implemented a custom method selectThing to set the TextView text.
  • Updating activity_thing.xml; replacing the TextView with the ThingFragment.
  • Updating ThingActivity; replacing setting the TextView text with a call to the custom method selectThing.
Now let us move to MainFragment; this time will share the changes in the commit.  Again, we start with the wizard.  The gist is as follows:
  • Bring layout from activity_main.xml to fragment_main.xml
  • Bring functionality from MainActivity to MainFragment
At this point, we leave out the complexity of the clicking for now.

note: Interestingly, when documenting JavaScript frameworks, I have found that I could include the source code changes in my documentation (as I have done thusfar), but Java / Android code is sufficiently heavy that I have had to change to using GIT commits (and their diffs). 


Ok, now we need to be able to take a click in MainFragment and have MainActivity do something with it; doing it as per the documentation.  At this point, we have gotten the code back to the original functionality.

Changes: https://github.com/larkintuckerllc/HelloAndroid/commit/b7766e8d201172f97e959b0a4e9b002f8c174104

Now, we need make it so that on a tablet we get a single screen with both fragments showing.

Changes: https://github.com/larkintuckerllc/HelloAndroid/commit/3a15f7efc286e79f05639238b63ec9904f078ab5

No comments:

Post a Comment