i added the fragment using XML and it worked fine , but when i tried to add it dynamically it did not appear in the main activity
FragmentActivity.java:
package com.example.pc.learn_again;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.PersistableBundle;
public class FragmentActivity2 extends Activity{
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.mainfragment2);
//adding the fragment using Java code---dynamically ya3ni//
//create an object of the intended frag//
Fragment3 frag = new Fragment3();
//get the manager
FragmentManager manager = getFragmentManager();
//start the transaction
FragmentTransaction transaction = manager.beginTransaction();
//add to the layout
transaction.add(R.id.mylayout,frag,"fragment3");//--note: the parameters used are 1- the id of the main layout 2- the intended fragment 3- a key for future use//
//finish using the below
transaction.commit();
}
}
Fragment3.java:
package com.example.pc.learn_again;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment3,container,false);
}
}
the fragment3.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/highlighted_text_material_light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView3"
android:layout_gravity="center_horizontal"
android:layout_margin="40dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button12"
android:layout_below="@+id/textView3"
android:layout_margin="40dp"
android:layout_gravity="center_horizontal" />
</RelativeLayout>
the mainfragment2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mylayout">
</LinearLayout>
i checked all of the above and the connection between the xml files and the classes and all are correct though when i test it the fragment does not show in the activity