How to add an Android fragment to an activity?

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

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