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?
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With