fragment placehoder in layout
Solution 1
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();
Solution 2
You can also use FragmentContainerView. From the documentation:
FragmentContainerView is a customized Layout designed specifically for Fragments. It extends FrameLayout, so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.
Example (also from the docs):
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.fragment.app.FragmentContainerView>
Comments
-
Leem.fin almost 2 years
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?
-
Leem.fin about 12 yearsft.replace(...) should be changed to ft.add(...) in my case.
-
Hardy over 9 yearsSee this for more info: developer.android.com/training/basics/fragments/…