03A Fragments and MVC Flashcards
Fragments
• A fragment is an independent module with its own user interface
• You can create a fragment without a UI to
handle background tasks, but this is not the usual case
• Fragments exist only when embedded within an Activity
Creating Fragments
• Within Android Studio you can right-click on the “app” root, select New, and select
Fragment
• You’ll be presented with three choices:
– Fragment (blank)
– Fragment (list)
– Fragment (with a +1 button)
• Your fragment will have a layout defined in the XML
• The code for your fragment will be an inner class within the main class
• Your fragment extends the Fragment class
• If you have a UI, override the
onCreateView method to inflate it
The Fragment Lifecycle
Fragment.onAttach->Fragment.onCreate-> Fragment.onCreateView-> Fragment.onActivityCreated (Visible) Fragment.onStart-> (Active)
Fragment.onResume->Fragment->onPause-> Fragment->onPause-> Fragment.onDestroyView-> Fragment-> onDestroy->Fragment->onDetach
Fragments and Activities
• You can get a reference to the activity in
which the fragment exists:
MainActivity main = (MainActivity)getActivity();
Compound Controls
- Compound controls are self-contained View Groups that contain multiple child views
- These can be treated as a single control
Model-View-Controller (intro)
- This paradigm is used for many controls, but in particular, you’ll need it for lists
- The Model is the actual data
- The View is how the data are displayed
- The Controller gets input
MVC (JList)
- JList does not have an “add” method
- Therefore, to add something to the list on the screen, you must add it to the model
- The View implements ActionListener to get events from the model when the data changes
- Views can show the data in different ways, depending upon the renderer
JSpinner Models
- The JSpinner control has several models:
- SpinnerDateModel to cycle through dates • SpinnerNumberModel for numbers (default)
- SpinnerListModel cycles through the items in a list
The JList Control Revisited
• The appearance of JList is controlled by the
Cell Renderer
• These implement the ListCellRenderer
interface, which defines the
getListCellRendererComponent method
• Thus the appropriate Cell Renderer can
display anything in a list
• ListCellRenderer subclasses should handle the cases where the cell is selected and where it is not, and whether it has the focus
• These attributes are passed as parameters to the getListCellRenderer method