Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change fragment's class dynamically

Hi I have a linearLayout containing two fragments and I add tabs with code to this layout. What I want is when I click tab1 it is ok to fragment fill itself from indicated class, but in tab2 I want to change this class to another class. Thank you

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frags">

   <fragment class="com.tugce.MitsActionBar.DoktorlarFragment"
            android:id="@+id/frag_title"
            android:visibility="gone"
            android:layout_marginTop="?android:attr/actionBarSize"
            android:layout_width="@dimen/titles_size"
            android:layout_height="match_parent" /> 

    <fragment class="com.tugce.MitsActionBar.ContentFragment"
            android:id="@+id/frag_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
like image 696
tugce Avatar asked Sep 15 '11 13:09

tugce


2 Answers

Change <fragment/> in xml layout to <FrameLayout/>

<FrameLayout
        android:id="@+id/frag_title"
        android:visibility="gone"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:layout_width="@dimen/titles_size"
        android:layout_height="match_parent" /> 

<FrameLayout
        android:id="@+id/frag_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

and add fragments programmatically:

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

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.replace(R.id.frag_content, fragment);
fragmentTransaction.commit();

But at first read this.

like image 104
pawelzieba Avatar answered Nov 16 '22 16:11

pawelzieba


Shortest version of calling a fragment

getFragmentManager().beginTransaction().replace(R.id.splash_container, new ExampleFragment()).addToBackStack(null).commit();

addToBackStack(null) is optional if you want to save the fragment on stack or not..

like image 23
Zar E Ahmer Avatar answered Nov 16 '22 17:11

Zar E Ahmer