====== Chapter 8 ====== ===== pp. 328-329 ===== Don't get discouraged if you miss a lot of the details in converting the code. The authors pretty much throw you into the deep end with this exercise. Be sure to study the solution on pp. 330-331 and make sure you understand why each change is necessary. The summary of converting Activities to Fragments is: * Change the class name to ''{whatever}Fragment'' and change the parent class to ''Fragment''. * Make all lifecycle methods public. * Define an ''onCreateView'' method in which you inflate the layout. * Remove any cruft from the lifecycle methods. * Be very careful about when/where/how Views are accessed (esp. anything that relies on the parent's layout) and refactor the code as needed. The last item above is often the most challenging. ===== pp. 332-334: Code block ===== package com.hfad.workout; import android.os.Bundle; import android.os.Handler; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class StopwatchFragment extends Fragment { //Number of seconds displayed on the stopwatch. private int seconds = 0; //Is the stopwatch running? private boolean running; private boolean wasRunning; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { seconds = savedInstanceState.getInt("seconds"); running = savedInstanceState.getBoolean("running"); wasRunning = savedInstanceState.getBoolean("wasRunning"); if (wasRunning) { running = true; } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_stopwatch, container, false); runTimer(layout); return layout; } @Override public void onPause() { super.onPause(); wasRunning = running; running = false; } @Override public void onResume() { super.onResume(); if (wasRunning) { running = true; } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putInt("seconds", seconds); savedInstanceState.putBoolean("running", running); savedInstanceState.putBoolean("wasRunning", wasRunning); } public void onClickStart(View view) { running = true; } public void onClickStop(View view) { running = false; } public void onClickReset(View view) { running = false; seconds = 0; } private void runTimer(View view) { final TextView timeView = (TextView) view.findViewById(R.id.time_view); final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { int hours = seconds / 3600; int minutes = (seconds % 3600) / 60; int secs = seconds % 60; String time = String.format("%d:%02d:%02d", hours, minutes, secs); timeView.setText(time); if (running) { seconds++; } handler.postDelayed(this, 1000); } }); } } ===== pp. 335-336: Code block =====