[android] How do I start an activity from within a Fragment?

I have a set of tabs inside of a FragmentActivity that each hold their own fragment. When I tried to start a new activity from within that fragment via an onClickListener, and using the startActivity(myIntent) method, my application force closes.

After looking around for a while, I found a reference or two to a method called startActivityFromFragment, but after searching around for an hour or so I can't find any explanations or examples of how to use it or whether this is what I should be using.

I guess what I'm asking is whether there is any difference between launching a new activity from an activity, and launching a new activity from a fragment, and if so, what do I need to implement?

This question is related to android android-activity fragment

The answer is


I done it, below code is working for me....

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

        Button newPage = (Button)v.findViewById(R.id.click);
        newPage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HomeActivity.class);
                startActivity(intent);
            }
        });
        return v;
    }

and Please make sure that your destination activity should be register in Manifest.xml file,

but in my case all tabs are not shown in HomeActivity, is any solution for that ?


The difference between starting an Activity from a Fragment and an Activity is how you get the context, because in both cases it has to be an activity.

From an activity: The context is the current activity (this)

Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);

From a fragment: The context is the parent activity (getActivity()). Notice, that the fragment itself can start the activity via startActivity(), this is not necessary to be done from the activity.

Intent intent = new Intent(getActivity(), NewActivity.class);
startActivity(intent);

I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:

In the MenuFragment class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_menu, container, false);

    final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
    sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "sendFreeTextButton clicked");
            Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
            MenuFragment.this.startActivity(intent);
        }
    });
    ...

You should do it with getActivity().startActivity(myIntent)


Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to fragment

FragmentActivity to Fragment Handling back button in Android Navigation Component android.content.Context.getPackageName()' on a null object reference Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment How to move from one fragment to another fragment on click of an ImageView in Android? Android - save/restore fragment state Intent from Fragment to Activity Get the Application Context In Fragment In Android? Add Items to ListView - Android Using onBackPressed() in Android Fragments