我的导航抽屉菜单有替换内容框架,但我不知道如何设置默认的主页片段。
这是我的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = getResources().getStringArray(R.array.menu);
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu);
dList.setAdapter(adapter);
dList.setSelector(R.color.pick);
dList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = null;
FragmentManager FM = getFragmentManager();
switch (position) {
case 0:
detail = new HomeFragment();
break;
case 1:
detail = new DataBase();
break;
case 2:
detail = new MappingFragment();
break;
case 3:
detail = new HelpFragment();
break;
default:
break;
}
FM.beginTransaction().replace(R.id.content_frame, detail).commit();
}
});
}
我想将HomeFragment设置为默认选择/主页
default:
detail = new HomeFragment();
break;
如果没有其他情况适用,则选择默认情况
谢谢你的回答,问题解决了。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu = getResources().getStringArray(R.array.menu);
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menu);
Fragment home = new HomeFragment();
FragmentManager FM = getFragmentManager();
FM
.beginTransaction()
.replace(R.id.content_frame, home)
.commit();
dList.setAdapter(adapter);
dList.setSelector(R.color.pick);
dList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = null;
FragmentManager FM = getFragmentManager();
switch (position) {
case 0:
detail = new HomeFragment();
break;
case 1:
detail = new DataBase();
break;
case 2:
detail = new MappingFragment();
break;
case 3:
detail = new HelpFragment();
break;
default:
break;
}
FM.beginTransaction().replace(R.id.content_frame, detail).commit();
}
});
}
在主活动的onCreate方法中添加以下代码:
getFragmentManager().beginTrasaction().replace(r.id.frame_layout, new HomeFragment()).commit();
在导航抽屉中,更好的解决方案是在onCreate方法中添加以下代码:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FRAGMENT_CLASS_NAME_HERE()).commit();
navigationView.setCheckedItem(R.id.DRAWE_NAV_ITEM_ID_HERE);
}
这比许多其他选项简单得多,并且还选择了导航菜单项。