我已经在Android开发人员上使用Nav Drawer示例实现了一个多视图应用程序,一切正常并且正确实现。我使用动态加载片段的方式。我有一个主要活动加载片段框架容器。当我在导航抽屉中选择选项时我的onclick监听器允许我更改片段而没有任何问题并将它们加载到框架容器中。此框架容器包含在我的主活动xml文件中。相关的id在oncreate方法中与它应该完全相同,这很好。我遇到的问题是这个活动在加载时显然是空白的,我希望它从我的字符串数组填充第一个项目,而不必触摸导航菜单。我确信解决方案很简单,但它仍然在逃避我!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
\\ this loads my content frame to display a fragment when i select a nav bar option
setContentView(R.layout.activity_my);
activity_my.xml
<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 -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:entries="@array/futurists"
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>
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayView(position);
}
}
// Method that updates content frame with different fragments
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Title();
break;
case 1:
fragment = new Activity1();
break;
case 2:
fragment = new Activity2();
break;
case 3:
fragment = new Activity3();
break;
case 4:
fragment = new Activity4();
break;
case 5:
fragment = new Activity5();
break;
case 6:
fragment = new Activity6();
break;
case 7:
fragment = new Activity7();
break;
case 8:
fragment = new Activity8();
break;
case 9:
fragment = new Activity9();
break;
case 10:
fragment = new Activity10();
default:
break;
}
if (fragment != null)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).addToBackStack(null).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNames[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
上面是我的onclick监听器,它在内容框架中选择用于填充的各种片段。
我的问题是如何加载片段标题而不必在活动加载时触摸导航抽屉中的选项。我正在查看应用程序生命周期,我在oncreate方法之后尝试使用onCreateView进行各种实验,但这也没有用。任何帮助将不胜感激。谢谢