【发布时间】:2014-09-02 22:26:06
【问题描述】:
我的情况是包含 Fragment B 的 Activity A。我总是这样实现它。
活动 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" />
片段 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>
这很好用,但是如果我们打开 Android 设备监视器并查看 View Hierarchy:
所以,我不喜欢在我的层次结构中有两个相同的无用 FrameLayouts,我可以剪切我的 R.id.container。我是这样做的:
我的活动 A 中的 onCreate(Bundle args) 实现:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.add(android.R.id.content, FragmentB.newInstance()).commit();
}
我只是没有为我的 Activity 设置内容,而是将我的 Fragment B 附加到系统容器 android.R.id.content。这对我很有用。我删除了一个无用的包含。
我的问题是做这个“hack”是个好习惯。它会在任何情况下使我的应用程序崩溃吗?在此实施后我会遇到什么问题?可能有人在这个问题上有有用的经验吗?
感谢大家的好回答。
【问题讨论】:
-
same不,android.R.
标签: android android-layout android-fragments fragmenttransaction