Is it possible to have a fragment without an activity?

Fragments are part of the activity, so they cannot replace activity. Though they behave like activity, they cannot stand themselves. Its like view cannot itself act like activity.

From Android Developers:

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. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

I hope it is helpful to you.


Well as people have pointed out you can't, but, you can always create some sort of fragment wrapper. For example purposes:

    public class ActivityFragmentWrapper extends FragmentActivity {
        public static final String KEY_FRAGMENT_CLASS = "keyFragmentClass";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getIntent().getExtras() != null) {
                String fragmentClass = (String) getIntent().getExtras().get(KEY_FRAGMENT_CLASS);
                try {
                    Class<?> cls = Class.forName(fragmentClass);
                    Constructor<?> constructor = cls.getConstructor();
                    Fragment fragment = (Fragment) constructor.newInstance();
                    // do some managing or add fragment to activity
                    getFragmentManager().beginTransaction().add(fragment, "bla").commit();
                } catch (Exception LetsHopeWeCanIgnoreThis) {
                }
            }
        }

        public static void startActivityWithFragment(Context context, String classPathName) {
            Intent intent = new Intent(context, ActivityFragmentWrapper.class);
            intent.putExtra(KEY_FRAGMENT_CLASS, classPathName);
            context.startActivity(intent);
        }
    }

You can start it like:

    ActivityFragmentWrapper.startActivityWithFragment(context, SomeSpecificFragment.class.getCanonicalName().toString());

Of course if your fragment has another constructor you have to retrieve different one, but that part gets easier.

Tags:

Android