I am having a hard time figuring out why my FragmentManager isn't working.
I'm using an Android studio template for nav drawer activity. The most confusing thing is, I have the exact same code in another app and it works just fine.
Here is the code:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.nav_camera:
fragment = new MyFragment();
Log.i("ID", String.valueOf(id));
break;
case R.id.nav_gallery:
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_main, fragment)
.commit();
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Now, when I click on the nav_camera it logs the click just fine, but nothing else happens, the fragment doesn't get replaced. No errors, no exceptions, just the same screen over and over.
Fragment code, nothing here just testing:
public class MyFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Fragment layout, just a blank:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
The rest of the code is auto generated by andorid studio.
Here is content_main, which I am trying to replace with fm:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_main"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.goran.mymoviedb.movies.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
It should replace the layout with a blank one whan nav_camera is clicked but nothing happens, even though correct click is registered.
Actually your code is working but the issue is that you have blank layout and because background of fragment layout is by default transparent you can not see the change. Put background color on your root layout of fragment (LinearLayout) for example: android:background="#android:color/white"
and you will see fragement replacement.
I wanna open fragment from my activity. The problem is that the fragment never appears.
This is the part of my activity:
btn_opciones.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
#Override
public void onValueChanged(int position) {
if(position == 1){
OrdenarComplejosFragment ordenarComplejosFragment = new OrdenarComplejosFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.add(ordenarComplejosFragment, null);
ft.commit();
}
}
});
And this is my fragment that I wanna open and show:
public class OrdenarComplejosFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ordenar_complejos, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//do your stuff for your fragment here
}
}
The xml of the fragment above:
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="HOLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
android:id="#+id/textView35"
android:layout_gravity="center_horizontal" />
</LinearLayout>
I don't know why the fragment never show. The button works fine.
Try using a different "add" method. Using the one which takes in a view id indicates where the fragment should show up within the existing Activity's layout.
ft.add(R.id.fragment_frame, ordenarComplejosFragment);
Fragments are always housed within an Activity. If your activity doesn't provide a container/location for the fragment to show up, you'll need to re-think the layout or consider opening this new view with a separate Activity.
I am trying to move from one fragment to another.. It shows following error during fragment transaction-
java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2{41a57218 #3 id=0x1020002}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
Below are the classes.I have used following code for fragment transaction
Fragment fragment = new PhotosFragment2();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
PhotosFragment.java
public class PhotosFragment extends Fragment {
private FragmentActivity myContext;
#Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos, container, false);
rootView.setVerticalScrollBarEnabled(false);
int[] mThumbIds = {
R.drawable.album8, R.drawable.album3,
R.drawable.album4, R.drawable.album8,
R.drawable.album6, R.drawable.album7,
R.drawable.album12, R.drawable.album10,
};
int[] mThumbIds2 = {
R.drawable.album8, R.drawable.album3,
R.drawable.album4,
R.drawable.album6, R.drawable.album7,
R.drawable.album9, R.drawable.album10,
R.drawable.album11, R.drawable.album12, R.drawable.album8,
R.drawable.album8, R.drawable.album3,
R.drawable.album4,
R.drawable.album6, R.drawable.album7,
R.drawable.album9, R.drawable.album10,
R.drawable.album11, R.drawable.album12, R.drawable.album8,
};
CustomGridSingle2 adapter = new CustomGridSingle2(myContext, mThumbIds);
GridView grid = (GridView)rootView.findViewById(R.id.gridView);
final ImageView img= (ImageView)rootView.findViewById(R.id.imageView7);
grid.setFocusable(false);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new PhotosFragment2();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
});
CustomGridSingle2 adapter2 = new CustomGridSingle2(myContext, mThumbIds2);
GridView grid2 = (GridView)rootView.findViewById(R.id.gridView2);
grid2.setFocusable(false);
grid2.setAdapter(adapter2);
grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = new PhotosFragment2();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
});
return rootView;
}
}
PhotosFragment2.java
public class PhotosFragment2 extends Fragment {
private FragmentActivity myContext;
#Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.photos2, container, false);
myContext.getActionBar().hide();
return rootView;
}
}
Activity xml file
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/bgmenu"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/profilelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:paddingTop="10dp">
<ImageView
android:id="#+id/drawer_profile_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/drawer_profile_background"
android:layout_alignLeft="#+id/drawer_profile_background"
android:layout_alignRight="#+id/drawer_profile_background"
android:layout_alignTop="#+id/drawer_profile_background"
android:layout_marginBottom="7.667dp"
android:layout_marginLeft="6.5dp"
android:layout_marginRight="8.3dp"
android:layout_marginTop="7.667dp"
android:scaleType="centerCrop"></ImageView>
<ImageView
android:id="#+id/drawer_profile_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:scaleType="centerCrop"
android:src="#drawable/profileblock">
</ImageView>
<ImageView
android:id="#+id/settingicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/drawer_profile_background"
android:layout_marginLeft="-15dp"
android:layout_toRightOf="#+id/drawer_profile_background"
android:background="#drawable/settings" />
<textview
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/drawer_profile_background"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#android:color/white" />
</RelativeLayout>
<ListView
android:id="#+id/list_slidermenu"
style="#style/buttonStyle"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="30dp"
android:layout_weight="2"
android:cacheColorHint="#android:color/transparent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="1dp"
android:listSelector="#android:color/transparent"
android:scrollbars="none" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
When you use fragmentTransaction.replace(R.id.container,fragment) it will remove any fragments that are already in the container and add your new one to the same container.
Now i can suggest you 2 things.First, if you want to use fragmentTransaction.replace(android.R.id.content, fragment); which you are doing right now,then don't set content for your Activity using setContentView.This should work fine then.To know what exactly android.R.id.content is you can refer this stackoverflow question and answer
Or Secondly, In the layout of your Activity have a FrameLayout whose id is content. And then use
fragmentTransaction.replace(R.id.content, fragment);
fragmentTransaction.addToBackStack(null);//add the transaction to the back stack so the user can navigate back
// Commit the transaction
fragmentTransaction.commit();
Hope this helps.
More Info:
From your comments it seems that you are having some problem in getting the idea of using FrameLayout in your Activity's layout(Not of any of the Fragment's layout).From the Documents
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.
So the main purpose of FrameLayout is to block the area required to fit the largest child view. If you use a FrameLayout as Fragment Container you can ensure that you always have the space available to accommodate the largest Fragment's layout.
So you can have your FrameLayout something like this in your Activity's layout xml file
<FrameLayout
android:id="#+id/content"
android:layout_height="match_parent"
android:layout_width="match_parent">
<!--you can put your existing views of your current xml here, so yes your entire xml is now inside this FrameLayout -->
</FrameLayout>
I don't use getSupportFragmentManager().
I use getChildFragmentManager() and it worked for me.
You can try it.
If you are trying to put Fragment into Fragment, use getChildFragmentManager()
If you are using ViewPager, use getChildFragmentManager() for pager adapter
viewPager.setAdapter(new ItemsAdapter(getChildFragmentManager()));
You have to set a content view in your Activity that your PhotosFragment is attached.
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
//...
}
i know this is very late. But it may work for other's.
I declared the id for each layout, like (3rd line bellow)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
Since Android 4.2 (API 17) nested fragments become avaliable.
See this
To place fragment inside other fragment use getChildFragmentManager()
Also available in support library.
I had the same error and after trying a lot of things I found that the problem was with the "id" and "getActivity().getSupportFragmentManager()".
Before i implement i like these
txt_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getChildFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new OpportunitiesFragment())
.commit(); }
});
Then i changed to these
txt_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
## Heading ##
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new OpportunitiesFragment())
.commit(); }
});
Put this block of code in PhotosFragment2 onCreateView method:
View rootView = inflater.inflate(R.layout.photos2, null);
instead of:
View rootView = inflater.inflate(R.layout.photos2, container, false);
in my case I had to change
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.sample,
container);
to
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.sample,
container, false);
This answer highlights a silly mistake that may occur, that arises when nesting fragments or you are converting activities to fragments.
If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.
In BaseFragment.java OnCreateView:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new DifferentFragment())
.commit();
}
return super.onCreateView(inflater, container, savedInstanceState);
Replace super.onCreateView(inflater, container, savedInstanceState);
with inflating the correct layout for the fragment:
return inflater.inflate(R.layout.base_fragment, container, false);
The problem may be that you add a fragment and beginTransaction in some fragment like
getFragmentManager().beginTransaction().replace(android.R.id.content, ImageBrowseFragment.newInstance(bundle),"ImageBrowseFragment")
.addToBackStack(null).commit();
I just change getFragmentManager() to getActivity().getSupportFragmentManager()
Then everything goes fine
When you add a fragment in a fragment use android.R.id.content Or Window.ID_ANDROID_CONTENT,I guess it represents the root container of your fragment not the activity. So change to getActivity().getSupportFragmentManager() works it out
If you use ViewPager with fragments (pages) and try to show a new fragment from a page, you will get this error. I think, you cannot reference to a container of an Activity from a ViewPager's page.
In this case you should call getActivity(). Then in Activity write a method that will open a new fragment.
class YourActivity : AppCompatActivity() {
fun showNewFragment(title: String) {
val fm = supportFragmentManager
fm?.beginTransaction()?.apply {
val fragment = NewFragment.newInstance(title)
replace(R.id.container, fragment, NewFragment.TAG)
addToBackStack(null)
}?.commit()
}
}
class PageFragment : Fragment() {
private fun show() {
(activity as YourActivity).showNewFragment("New fragment")
}
}
If you call getParentFragment() and add a new fragment, then you will place a new fragment inside ViewPager:
class ViewPagerFragment : Fragment() {
fun showNewFragment(title: String) {
val fm = childFragmentManager
fm?.beginTransaction()?.apply {
val fragment = NewFragment.newInstance(title)
replace(R.id.container, fragment, NewFragment.TAG)
addToBackStack(null)
}?.commit()
}
}
class PageFragment : Fragment() {
private fun show() {
(parentFragment as? ViewPagerFragment)?.showNewFragment("New fragment")
}
}
Make sure the fragment id you are calling is in the class listed in setcontent in onCreate method. For my case, I was editing the layout from linear to constraint. So as not to mess with the working code, I made another layout but messed an id in the process so that what was on oncreate was the edited layout but the fragment being called was from the old layout. Apparently, in the new layout I gave it a different id name. Search the id of your fragment using ctrl+shift+f and see if the search results point to the layout you specified in the oncreate method. Goodluck.
The most common mistake that can be happened is, If you have more than one version of XML layout (let say v21 and v23) and you added <fragment> tag in lower version of XML only (or vice-versa).
So, please check you added <fragment> tag (or pageGroup, etc) in both of the versions.
You are trying to open fragment which fragmentContainer(the view in which you are trying to open fragment) is one or more level above from your current fragmentContainer.
Try to change your fragment hierarchy architecture.
I'm trying to put 2 fragments inside a fragment. I found some code on internet but, as far as I could go, I don't succeed to put 2 fragments in 1 fragment.
I have seen tips dealing with FragmentManager and especially the method getChildFragmentManager() but I don't know how it works with 2 fragments.
For the story, I'm using an activity with ActionBar which creates 3 fragments. In one of them, I need to handle a graph and a kind of menu to change the graph scale. In this way, I need 2 fragments in one fragment.
Here is the code :
The fragment which handles the others:
public class GraphDisplayFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.graph_fragment, container, false);
return myFragmentView;
}
}
The code to draw the graph:
public class GraphFragment extends Fragment {
private static final int SERIES_NR = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
GraphicalView myFragmentView = ChartFactory.getTimeChartView(this.getActivity(), getDateDemoDataset(), getDemoRenderer(),null);
return myFragmentView;
}
//some functions to set graph propreties
}
The XML files :
graph_fragment.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" >
<fragment
android:id="#+id/graph_fragment"
android:name="com.test.GraphFragment"
android:layout_width="match_parent"
android:layout_height="259dp" >
</fragment>
<fragment
android:name="com.test.GraphDetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph_detail_fragment">
</fragment>
</LinearLayout>
graph_detail.xml with a test implementation
<?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" >
<TextView
android:id="#+id/textView1"
android:layout_width="211dp"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
The weird thing is, it works at the begining when I switch between fragments in the ActionBar but after 3-4 moves, I get this error :
android.view.InflateException: Binary XML file line #7: Error inflating class fragment
If anyone has the solution, it would be awesome!
So first off change your xml for graph_fragment.xml to this
<?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" >
<FrameLayout
android:id="#+id/graph_fragment_holder"
android:layout_width="match_parent"
android:layout_height="259dp" >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph_detail_fragment_holder">
</FrameLayout>
</LinearLayout>
Then in code to inflate them from the fragment use something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.graph_fragment,
container, false);
FirstChildFragment frag1 = (FirstChildFragment) getChildFragmentManager()
.findFragmentById(R.id.first_frag_layout);
SecondChildFragment frag1 = (SecondChildFragment) getChildFragmentManager()
.findFragmentById(R.id.second_frag_layout);
if (null == frag1) {
FirstChildFragment = new frag1();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.add(R.id.graph_fragment_holder, frag1)
.addToBackStack(null).commit();
}
if (null == frag2) {
SecondChildFragment = new frag2();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.add(R.id.graph_detail_fragment_holder, frag2)
.addToBackStack(null).commit();
}
return rootView;
}
MyFragment myFragment = (MyFragment)getChildFragmentManager().findFragmentById(R.id.my_fragment);
You can try to use the method *findFragmentById(fragment_id)* from SupportFragmentManager to get the instance of fragment from your .xml file and insert your fragment there.
Something like:
Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.myFragmentId);
I hope to help you.
Best regards.
Adriano
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;
}
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 />
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" />
Make sure the activity that has the activity_main.xml layout extends FragmentActivity and not Activity.
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();
}
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();
}