A Fragment shall be associated with a Activity so that it can be displayed. For this you must define a space within the Activity(a container). Here is an example.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:background="@android:color/white"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
The space that the Linear Layout id container will be the space available for the Fragment
If you use the Appcompat library you can display a Fragment
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MenuFragment())
.commit();
Where container is the Linearlayout I defined and Menufragment is the Fragment I wish to display.
If you do not use appcompat the code is similar follows below:
Fragment fr = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();
These calls from Fragment can be made both of a Fragment to each other as inside a Activity
To make the call inside a Fragment at the click of the button just put the code inside the setOnClickListener
button.
Obg! It worked,
– Douglas William
Caique, in my case I have a Linearlayout and inside it a include where I am placing my Fragment. I tried to do what you suggest above, but when putting the id or the Linearlayout or the include does not recognize gives the following message "Cannot resolve method 'add(int)' "
– GustavoSevero