Java how to start activity from fragment inside?

Java how to start activity from fragment inside?

To start an activity from a fragment in Java, you can use the startActivity method of the Fragment class and pass it an Intent that specifies the activity to be started.

Here's an example of how you can do this:

refer to:‮‬lautturi.com
public class MyFragment extends Fragment {
    public void startActivityExample() {
        Intent intent = new Intent(getActivity(), ExampleActivity.class);
        startActivity(intent);
    }
}

This code will start the ExampleActivity activity from within the fragment.

Alternatively, you can use the getContext method of the Fragment class to get a Context object, and then use the startActivity method of the Context class to start the activity.

Here's an example of how you can do this:

public class MyFragment extends Fragment {
    public void startActivityExample() {
        Intent intent = new Intent(getContext(), ExampleActivity.class);
        getContext().startActivity(intent);
    }
}

Both of these approaches will work in most cases, but if you need to start an activity from a fragment that is not attached to an activity, you may need to use the getActivity method to get a reference to the activity .

Created Time:2017-11-03 23:27:07  Author:lautturi