Android Fragment quick start

Step 1: Create activity layout

Name it: test_activity.xml


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/fragment_container</span>"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/white" >
</FrameLayout>

Note the id of fragment container (@+id/fragment_container). All fragments will be inflate to this id.

Step 2: Create fragments layout

We name it: test_fragment.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" >

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fragment sample" />

</RelativeLayout>

This is a fragment, in which there is a TextView.

Step 3: Fragment code

Create class and extend android.support.v4.app.Fragment (or android.app.Fragment).

public class TestFragment extends Fragment {

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.test_fragment, container, false);
    return v;
  }
}

onCreateView() is where we configure the layout of fragment (can treat it like Activity.onCreate())
In it, we inflate the layout with template from frag_practice.xml created above.

Step 4: Activity code

Create class and extend android.support.v4.app.FragmentActivity (or android.app.FragmentActivity).
public class TestActitivity extends FragmentActivity {

public class TestActitivity extends FragmentActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    setContentView(R.layout.test_activity);

    switchToFragment(new TestFragment());
  }

  void switchToFragment(Fragment newFrag) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, newFrag);
    transaction.commit();
  }

}

Leave a comment