marte marte - 3 months ago 22
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() {
@Override
public void onClick(View view) {

}
});


What i'm going to put inside this.

Answer

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="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

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

 <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me" />

 </LinearLayout>

Java

btnHome.setOnClickListener(new View.OnClickListener() {
    @Override
    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 (R.id.myFrame, myfragment);
  fragmentTransaction.commit ();

    }
});

See this doc

Comments