'How to add an Android fragment to an activity?

I would like to add a fragment to my main activity, so I have this fragment class (TitleFragment.java):

package com.myapp.app1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TitleFragment extends Fragment {
    @Override
    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="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
       <ImageView 
        android:id="@+id/logo_iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/logo_main"
        android:contentDescription="@string/app_name"
        android:scaleType="fitStart"
        android:adjustViewBounds="true" />
</LinearLayout>

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

<fragment 
            android:name="com.myapp.app1.TitleFragment"
            android:id="@+id/title_fragment"
            android:layout_width="0dp"
            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.



Solution 1:[1]

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(R.id.body_frame, new MyFragment()).commit();

in your case, it should look like:

FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.title_fragment, 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();

Edited:

you should modify your fragment class:

@Override
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;
}

Solution 2:[2]

In fragment seccion add

tools:layout="@layout/fragment_title

like this


<fragment 
    android:name="com.myapp.app1.TitleFragment"
    android:id="@+id/title_fragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    tools:layout="@layout/fragment_title />

Solution 3:[3]

You can do that simply like this and declare the name of fragment:

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

Solution 4:[4]

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

Solution 5:[5]

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

//function that does the trasaction when a fragment object is passed
//R.id.container is my default frame
public void fragmentChanger(String title, Object expectedFragment){
   // mToolBarTextView.setText(title);
    transaction = fragmentManager.beginTransaction();
    transaction.replace(R.id.container, (Fragment) expectedFragment);
    transaction.addToBackStack(null);
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    transaction.commit();
}

Solution 6:[6]

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 ();
   getSupportFragmentManager().beginTransaction().add(R.id.frame_layout,blankFragmentA,BLANK_FRAGMENT_A).commit();
}

Replace Fragment

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Miguel Ángel Retamozo Sanchez
Solution 3 Dev Soni
Solution 4 Akash
Solution 5 Kevin Muchwat
Solution 6 Farid Haq