How to call a Fragment from an Activity button

Asked

Viewed 6,645 times

2

I have three Ragments and an Activity. In this Activity I have a button, how do I call a Fragment from that button ? I have a Fragment that has a button from that button I need to call another Fragment.

I know how to call activities with the following code snippet:

Intent it = new Intent(this, Activity.class);
startActivity(it);

1 answer

2


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,

  • 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)' "

Browser other questions tagged

You are not signed in. Login or sign up in order to post.