我认为您可能对 Activity 和 Fragments 有一些误解。一般规则是:
在片段中构建您的用户界面(在大多数情况下,一个Fragment
等于一
screen),然后使用 Activity 来排列和显示这些
碎片。
一个典型的Activity
布局与NavigationDrawer
看起来像这样:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<!-- This is the placeholder for your Fragments -->
<!-- You can display your Fragments here with FragmentTransactions -->
<FrameLayout
android:id="@+id/flFragmentPlaceHolder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<!-- It would even be better practice to use a Fragment here as well -->
<!-- But since the Google Tutorials just use a ListView here I will as well -->
<ListView android:id="@+id/lvDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
除了片段的占位符和片段的必要部分之外没有其他任何东西NavigationDrawer
应该在那个布局中。如果您想在Activity
在当前状态下,除了NavigationDrawer
可以从左侧拉入。您构建的任何用户界面稍后都将通过片段添加。
要显示一个Fragment
在该布局中你必须执行FragmentTransaction
。您可以添加、替换、删除、显示或隐藏多个Fragments
在一张单曲中FragmentTransaction
。在上面的示例中,您可能想要显示Fragment
其中包含用户的启动屏幕。为此,您需要执行FragmentTransaction
像这样:
// It is best practice to use factory methods to create Fragment instances
final Fragment fragment = StartupFragment.newInstance();
// There are multiple `FragmentManagers`, be sure to always use the right one!
FragmentManager manager = getFragmentManager();
// This starts the `FragmentTransaction`.
FragmentTransaction transaction = manager.beginTransaction();
// Now you can define what happens in this transactions
// You can add/replace/remove/hide or show as many Fragments
// as you want in one `FragmentTransaction`.
// This command specifically adds the Fragment to the placeholder we defined
// in the layout of the Activity
transaction.replace(R.id.flFragmentPlaceHolder, fragment);
// This commits the `FragmentTransaction`.
// Only after you call this will any changes be made
transaction.commit();
为了简洁起见,与上面相同的代码也可以写成:
final Fragment fragment = StartupFragment.newInstance();
getFragmentManager().beginTransaction()
.replace(R.id.flFragmentPlaceHolder, fragment)
.commit();
这样写的主要改进是你作为开发人员可以写它a lot速度更快,因为您几乎可以一直依赖代码完成。
如果稍后用户从NavigationDrawer
那么你只需要执行一个新的FragmentTransaction
来替换StartupFragment
与另一个不同的!