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 (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.

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

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

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 />

Build a flexible UI, beginTransaction(); fragmentTransaction.replace(android.R.id.content, 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 android.support.v4.app.FragmentTransaction ‘s add (), remove () or replace () method to operate Fragment.

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();
}

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 ();
   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();
}

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

Comments
  • 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.