How to call a fragment from an activity button

2

I have three fragments and one 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);
    
asked by anonymous 29.09.2015 / 19:44

1 answer

2

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.

    
29.09.2015 / 20:28