Java how to open an activity from a fragment

Java how to open an activity from a fragment

To open an activity from a fragment in Android, you can use the startActivity method of the Fragment class.

Here is an example of how you can open an activity from a fragment in Android:

refer t‮tual:o‬turi.com
import android.app.Fragment;
import android.content.Intent;

public class MyFragment extends Fragment {
    public void openActivity() {
        Intent intent = new Intent(getActivity(), MyActivity.class);
        startActivity(intent);
    }
}

In this example, the openActivity method is called to open the MyActivity activity from the MyFragment fragment. The Intent class is used to specify the target activity, and the startActivity method is used to start the activity.

Keep in mind that the Fragment class is a part of the Android Support Library, and you need to import it and add it to the dependencies of your project to use it in your Android app. You also need to declare the MyActivity activity in the AndroidManifest.xml file.

You can also use other methods and techniques to open an activity from a fragment in Android, such as using the FragmentTransaction class to replace the current fragment with the target fragment.

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