marte marte - 1 year ago 94
Android Question

Fragment on Activity

Hello i have a button inside my activity and when i click on this button i want to call a fragment.

For example if i want to call an activity i can use the intent but if i want to call a fragment, how i can do that.

I have check other question but i have not found what i'm asking.

btnHome.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {


What i'm going to put inside this.

Answer Source

You can add your fragment dynamically.You want to create a fragment.

To programmatically add or remove a Fragment, you will need the FragmentManager and FragmentTransaction

XML Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:orientation="vertical" >

    android:id="@+id/myFrame" <!-- Id which you're gonna use in Java -->
    android:layout_height="match_parent" />

    android:text="Click me" />



btnHome.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {

  FragmentManager fragmentManager = getFragmentManager ();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();

   MyFragment myfragment = new MyFragment();  //your fragment 

 // work here to change Activity fragments (add, remove, etc.). 
  fragmentTransaction.add (, myfragment);
  fragmentTransaction.commit ();


See this doc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download