FragmentActivity

This recipe is outdated! We’ll keep it for now, because it might be useful when maintaining old apps, but the new prefered way is to use a FragmentContainerView instead.

The new code replaces the FrameLayout in your layout with the xml below, and obviates the transaction in the onCreate method:

 <androidx.fragment.app.FragmentContainerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/fragment_container_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.pixplicity.example.ExampleFragment"
        android:tag="example_tag" />

Old exmple

You have a Fragment, but you want an Activity. This is a stupid thing to do and you should be using Fragments, ViewModels, etc. Here’s the copy-paste to do it anyway:

ExampleActivity.java

package com.pixplicity.example.activities;

import android.app.Activity;
import android.os.Bundle;

public class ExampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example);
        if (null == savedInstanceState) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, ExampleFragment.newInstance())
                    .commit();
        }
    }

}

activity_example.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pixplicity.example.activities.ExampleActivity" />