Intro to Android

Lab: Add CalculatorStateFragment

Create fragment

Create CalculatorStateFragment.java. This fragment will be a background frament that will manage the state of our calculator. Notice that we are returning a null view when creating the view.

public class CalculatorStateFragment extends Fragment
{
    @Override
    public View onCreateView( LayoutInflater inflater,
                              ViewGroup container,
                              Bundle savedInstanceState )
    {
        return null;
    }
}

Test fragment

Add the normal first test to our fragment file:

@RunWith (RobolectricTestRunner.class)

public class CalculatorStateFragmentTest
{
    @Test
    public void shouldNotBeNull() throws Exception
    {
        assertNotNull( new CalculatorStateFragment() );
    }
}

Test activity

Now add a test to CalculatorActivity to ensure that the fragment is present. It should fail!

@Test
public void shouldHaveCalculatorStateFragment() throws Exception
{
    assertNotNull( activity.getFragmentManager()
                           .findFragmentByTag( "calculator state" ) );
}

We're using findFragmentByTag() since this is a background fragment. When we add the fragment to the activity, we'll use a tag so that we can reference the fragment.

Now we have a reason to write code in the activity. First time this is starting to feel like real TDD!

Add CalculatorStateFragment to CalculatorActivity

Add a new instance of the fragment to our Activity's FragmentManager via a FragmentTransaction in onCreate().

    getFragmentManager().beginTransaction()
                        .add( new CalculatorStateFragment(),
                              CALCULATOR_STATE_FRAGMENT_TAG )
                        .commit();

Auto-generate a TAG for the calculator state fragment using the IDE.

Now retest - everything should pass.

Commit

Yay, time for a commit!