How to add an Android fragment to an activity?

how to add fragment in activity in android example
fragment overlapping in android
fragment android example
android fragment lifecycle
adding fragment to activity dynamically
add fragment to activity xml
android multiple fragments in one activity example
how to create fragment in android

I would like to add a fragment to my main activity, so I have this fragment class (

package com.myapp.app1;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TitleFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_title, container, false);

Next is the actual content of my fragment, contained in fragment_title.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >
        android:adjustViewBounds="true" />

And inside my activity_main.xml I have this snippet amongst the regular content of the activity:

            android:layout_height="match_parent" />

Is this method a correct way to create a fragment? My app just crashes and the LogCat seems to indicate it's to do with inflating the fragment view, but I'm not sure.

By the way the reason for this fragment is to have the app logo (image and some updateable text) that exists on every page, is this a good method to do something like that? Sorry for my newbie questions.

i have started fragment from my MainActivity. main activity extends FragmentActivity. the way i have used is:

FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(, new MyFragment()).commit();

in your case, it should look like:

FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(, new TitleFragment()).commit();

remember i have used an FragmentActivity to start Fragment. i have also used android-support-v4.jar to support fragment in lower version OS. without android-support-v4.jar, FragmentManager manager = getSupportFragmentManager(); may be look like : FragmentManager manager = getFragmentManager();


you should modify your fragment class:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_title, container, false);
    // you can use findViewById() using the above 'view'
      ....your code........
    return view;

Create a fragment, If your activity allows the fragments to be removed and replaced, you should add the initial fragment(s) to the activity during the activity's onCreate� To create a fragment, extend the Fragment class, then override key lifecycle methods to insert your app logic, similar to the way you would with an Activity class. One difference when creating a Fragment is that you must use the onCreateView () callback to define the layout.

In fragment seccion add


like this

    tools:layout="@layout/fragment_title />

Build a flexible UI, beginTransaction(); fragmentTransaction.replace(, fragment); fragmentTransaction.commit(); } }. To add a fragment into a Activity or� ::: There is no such thing "just" adding a fragment, usually the fragment is created depending on the screen size and orientation, otherwise an equivalent activity must be created. In the guide you will find code and explanations. – ilomambo Feb 19 '13 at 4:41

Make sure the activity that has the activity_main.xml layout extends FragmentActivity and not Activity.

How do I add a Fragment to an Activity with a programmatically , There are two ways to add a fragment to an activity: dynamically using Java and statically using XML. Before embedding a "support" fragment in an Activity make sure the Activity is changed to extend from FragmentActivity or AppCompatActivity which adds support for the fragment manager to all Android versions. Begin Fragment management transaction. FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction (); Create a new Fragment instance. Call ‘s add (), remove () or replace () method to operate Fragment.

public void onMenuItemClick(View clickedView, int position) {
    switch (position){
        case 1:
             fragmentChanger("Notifications",new notifyFragment());
        case 2:
             fragmentChanger("QR Code",new qrFragment());
        case 3:
            fragmentChanger("User ID",new MainFragment());
        case 4:
            fragmentChanger("Settings",new settingsFragment());
            Toast.makeText(this, "Clicked on position: " + position, Toast.LENGTH_SHORT).show();

//function that does the trasaction when a fragment object is passed
// is my default frame
public void fragmentChanger(String title, Object expectedFragment){
   // mToolBarTextView.setText(title);
    transaction = fragmentManager.beginTransaction();
    transaction.replace(, (Fragment) expectedFragment);

Creating and Using Fragments, You can add a fragment in two ways 1. Through the XML file 2. Add Fragment at Run Time For Duration: 11:13 Posted: Jan 3, 2018 Get real time updates directly on you device, subscribe now. Rather than defining the fragments for an activity in the layout file with the <fragment> element—you can add a fragment to an activity at runtime in Android app. This is necessary if you plan to change fragments during the life of the activity.

Using Tag you can add/Replace Fragment In Activity

private final static String BLANK_FRAGMENT_A= "BlankFragmentA";
private final static String BLANK_FRAGMENT_B= "BlankFragmentB";

private BlankFragmentA blankFragmentA;
private BlankFragmentB blankFragmentB;

Add Fragment

blankFragmentA= (BlankFragmentA) getSupportFragmentManager().findFragmentByTag(BLANK_FRAGMENT_A);
if (blankFragmentA== null) {
   blankFragmentA= new BlankFragmentA ();

Replace Fragment

blankFragmentB= (BlankFragmentB) getSupportFragmentManager().findFragmentByTag(BLANK_FRAGMENT_B);
if (blankFragmentB== null) {
   blankFragmentB= new BlankFragmentB();
   getSupportFragmentManager().beginTransaction().replace (,blankFragmentB,BLANK_FRAGMENT_B).commit();

Android tutorial (2018) - 10, In this video I am going to show you how to: add a fragment that we will create, to a activity Duration: 2:10 Posted: Oct 19, 2017 In this Android tip, I will show you how to send an intent from a fragment to an activity. Sending an intent from a fragment to an activity is almost the same as sending an intent from an activity to another activity except you need to pass a reference of the fragmen's hosting activity to the constructor of the Intent class.

How to add fragment to activity (xml method) Android Studio , In this video we'll learn how to display our Fragment inside the placeholder ViewGroup! The method, addToBackOfStack (String name), adds this transaction to the back stack, this can be used so that Fragments are remembered and can be used again by the Activity Let’s create an application using Fragment:- 1. Create a new fragment frag1 by Right click on App>select New>select Fragment>select Fragment (Blank).

Adding Fragments to Activities | Android Fragments, Use separate activities to host each fragment on a handset. An activity may include multiple fragments� While performing Fragment Transaction we can add a Fragment into back stack that’s managed by the Activity. back stack allow us to reverse a Fragment transaction on pressing Back button of device. For Example if we replace a Fragment and add it in back stack then on pressing the Back button on device it display the previous Fragment.

Building dynamic user interfaces in Android with fragments, Create and run apps in Android Studio. Use the layout editor to create a UI with a ConstraintLayout . Inflate the UI layout for an Activity . Add a set of radio buttons� In this video I am going to show you how to: add a fragment that we will create, to a activity using a fragment view in the layout file. This process will take about 2 minutes but by the time we

  • Post your LogCat stack trace. And the Action Bar already has the app logo and text that you can change.
  • The android.developers site has a good guide. ::: There is no such thing "just" adding a fragment, usually the fragment is created depending on the screen size and orientation, otherwise an equivalent activity must be created. In the guide you will find code and explanations.
  • I would up vote this but I don't have enough rep :( ^_^ Thanks, I had something very close to those three lines but not quite. I wonder if I should use the action bar rather than a fragment for my purposes though? Off to google!
  • I'd like to emphasize what is buried in one paragraph: If only targeting API 11 and newer, can do MainActivity extends Activity rather than MainActivity extends FragmentActivity. That is, Activitys can access Fragments, no longer need FragmentActivity. This approach would not use android-support-v4.jar. Instead of = getSupportFragmentManager(), do = getFragmentManager(). I know this is mentioned in the answer, but it would be easy to overlook or misunderstand what was said.
  • and what about extending ActionBarActivity with AppCompatv7
  • @ToKra That should be fine. ActionBarActivity is a child of FragmentActivity. More recently, it's been deprecated and defers to AppCompatActivity, which is also a child of FragmentActivity.
  • This answer is outdated: If targeting only API 11 and newer, Activity can be used, rather than FragmentActivity.