To quote the Android documentation,

A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.

Macroid allows you to deal with fragments, both and


For the below features to work, you need to include the right contexts:

import macroid.Contexts

class MyActivity extends Activity with Contexts[Activity] {

If you use fragments from the support library:

class MyActivity extends FragmentActivity with Contexts[FragmentActivity] {

Finally, in a fragment (either or

class MyFragment extends Fragment with Contexts[Fragment] {

The f word

Macroid provides an fragment (alised as f for short) brick, which is somewhat similar to the l and w bricks:


The fragment is created with its primary constructor, or with a newInstance method in its companion (or static method in Java fragments), if it exists. Like with w bricks, you can provide arguments to the newInstance method:

// same as FragmentClass.newInstance(arg1, arg2, ...)
f[FragmentClass](arg1, arg2, ...)

You can also put arguments into a Bundle and pass via the setArguments method:

// same as
// val b = new Bundle
// b.putXXX("arg1", arg1)
// b.putXXX("arg2", arg2)
// (new FragmentClass).setArguments(b)
f[FragmentClass].pass("arg1" → arg1, "arg2" → arg2, ...)

The factory method allows to obtain a fragment factory (Ui[FragmentClass]), which is very useful for creating fragment pagers:


Finally, here is a way to insert the fragment directly into the layout (it will be assigned a tag and wrapped into a FrameLayout). Note that for this to work, you need to create an id generator into your activity or parent fragment.

f[FragmentClass].pass(...).framed(Id.someId, Tag.someTag)

A more elaborate example: