A fragment must be associated with an activity so that it can be viewed. For this you must define a space inside activity (a container). Here's 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 Linear Layout with container id 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();
If you do not use appcompat the code looks similar to the following:
Fragment fr = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();
These fragment calls can be made from one fragment to another as well as within activity
To make the call within a fragment in the button click, just put the code inside the setOnClickListener
of the button.