My situation is Activity A which contains Fragment B. I always implement it like this.
Layout for Activity A:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Layout for Fragment B:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_title"
android:layout_centerInParent="true"
android:background="@drawable/green_button"
android:textColor="@android:color/white"/>
</RelativeLayout>
This works great, but if we open Android Device monitor and look at View Hierarchy:
So, I do not like that in my hierarchy there are two same useless FrameLayouts and I can cut my R.id.container. I do it like this:
onCreate(Bundle args) implementation in my Activity A:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.add(android.R.id.content, FragmentB.newInstance()).commit();
}
I just do not set content for my Activity and attach my Fragment B to system container android.R.id.content. This works great for me. I removed one useless include.
My question is it good practice to do this "hack". Could it crashs my application in any cases and what problems could I have after this implementation? May be somebody has useful experience in this question?
Thanks to all for good answers.