我已经使用 appcompat 库中的新工具栏来替换操作栏,并按照人们可能期望的那样使用导航抽屉进行设置。
我的问题是按下后退会最小化应用程序,而不是循环通过后台堆栈。如果我手动添加逻辑以onBackPressed()
弹出返回堆栈,这是一种解决方案,但会与导航抽屉当前选定的项目混淆。
activity_main.xml
<LinearLayout>
<android.support.v7.widget.Toolbar/>
<android.support.v4.widget.DrawerLayout>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView android:id="@+id/navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
MainActivity.java
private void setupDrawerAndToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(toggle);
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onNavigationDrawerItemSelected(position, true);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
List<NavigationDrawerItem> items = new ArrayList<>();
items.add(...);
drawerList.setAdapter(new NavigationDrawerAdapter(this, items));
drawerList.setItemChecked(selectedIndex, true);
}
...
private void onNavigationDrawerItemSelected(int position, boolean addToBackStack) {
if (position == selectedIndex) {
return;
}
selectedIndex = position;
// update the main content by replacing fragments
FragmentManager manager = getFragmentManager();
Fragment fragment;
switch (position) {
case ...:
fragment = new Fragment();
break;
default:
throw new IllegalArgumentException("invalid position");
}
FragmentTransaction transaction =
manager.beginTransaction()
.replace(R.id.container, fragment);
if (addToBackStack) {
transaction.addToBackStack(fragment.getClass().getName());
}
transaction.commit();
}