Class CannonGameFragment
(Fig. 6.6) overrides four Fragment
methods:
• onCreateView
(lines 17–28)—As you learned in Section 5.3.3, this method is called after a Fragment
’s onCreate
method to build and return a View
containing the Fragment
’s GUI. Lines 22–23 inflate the GUI. Line 26 gets a reference to the CannonGameFragment
’s CannonView
so that we can call its methods.
• onActivityCreated
(lines 31–38)—This method is called after the Fragment
’s host Activity
is created. Line 37 calls the Activity
’s setVolumeControlStream
method to allow the game’s audio volume to be controlled by the device’s volume keys.
• onPause
(lines 41–46)—When the MainActivity
is sent to the background (and thus, paused), the CannonGameFragment
’s method onPause
executes. Line 45 calls the CannonView
’s stopGame
method (Section 6.8.11) to stop the game loop.
• onDestroy
(lines 49–54)—When the MainActivity
is destroyed, its onDestroy
method calls the CannonGameFragment
’s onDestroy
. Line 46 calls the CannonView
’s releaseResources
method (Section 6.8.11) to release the sound resources.
1 // CannonGameFragment.java
2 // CannonGameFragment creates and manages a CannonView
3 package com.deitel.cannongame;
4
5 import android.app.Fragment;
6 import android.media.AudioManager;
7 import android.os.Bundle;
8 import android.view.LayoutInflater;
9 import android.view.View;
10 import android.view.ViewGroup;
11
12 public class CannonGameFragment extends Fragment
13 {
14 private CannonView cannonView; // custom view to display the game
15
16 // called when Fragment's view needs to be created
17 @Override
18 public View onCreateView(LayoutInflater inflater, ViewGroup container,
19 Bundle savedInstanceState)
20 {
21 super.onCreateView(inflater, container, savedInstanceState);
22 View view =
23 inflater.inflate(R.layout.fragment_game, container, false );
24
25 // get the CannonView
26 cannonView = (CannonView) view.findViewById(R.id.cannonView);
27 return view;
28 }
29
30 // set up volume control once Activity is created
31 @Override
32 public void onActivityCreated(Bundle savedInstanceState)
33 {
34 super.onActivityCreated(savedInstanceState);
35
36 // allow volume keys to set game volume
37 getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
38 }
39
40 // when MainActivity is paused, CannonGameFragment terminates the game
41 @Override
42 public void onPause()
43 {
44 super.onPause();
45 cannonView.stopGame(); // terminates the game
46 }
47
48 // when MainActivity is paused, CannonGameFragment releases resources
49 @Override
50 public void onDestroy()
51 {
52 super.onDestroy();
53 cannonView.releaseResources();
54 }
55 } // end class CannonGameFragment