Is it possible to have a fragment without activity?

This is unlikely, but it will potentially save me a lot of time to rewrite the same code. I want to implement a user interface using an alert-type service (e.g. Chathead), but I would still like to use my snippets. Is it possible? I know that I can add views to the window, but fragments?

+4
source share
2 answers

Fragments are part of the activity, so they cannot replace activity. Although they behave as activity, they cannot stand themselves. Such a view cannot act as activity.

From Android Developers :

A Fragment . . , , ( "sub ", ).

, .

+6

, , , - . , :

    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);
        }
    }

, :

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

, , , .

+2

All Articles