Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fragment placehoder in layout

Tags:

Suppose I have several fragments:

public class FirstFragment extends Fragment { ... }

public class SecondFragment extends Fragment { ... }

public class ThirdFragment extends Fragment { ... }

I have also a main activity, its content is (main.xml):

<LinearLayout ...>

  <!-- How to have a fragment placehold without specify which fragment show here? -->
  <fragment>

</LinearLayout>

My question is, in above layout file, how can I define a fragment placeholder without specify which fragment show here, and then in My Activity java code, inflate a proper fragment to the placeholder ?

Is it possible and how to do it?

like image 330
Leem.fin Avatar asked Mar 07 '12 10:03

Leem.fin


People also ask

What layout should I use for a fragment?

A FrameLayout is used because it's going to be the container of the Fragment. In other words, the Fragment will be stored inside of this layout.

Can we create fragment without layout?

However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.

How do I attach a fragment to an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.


1 Answers

It is possible. In your main.xml, define a place holder for the fragment, let's call it "fragment_placeholder":

<LinearLayout ...>
 <FrameLayout android:id="@+id/fragment_placeholder" android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />
</LinearLayout>

In your activity, whenever you want to load your fragment:

YourFragment fragment = new YourFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_placeholder, fragment);
ft.commit();
like image 82
Drimmka Avatar answered Sep 22 '22 12:09

Drimmka