我已成功使用抽屉布局设置导航抽屉。我发现删除这一简单的代码行会将汉堡包图标更改为后退按钮:
mDrawerToggle.syncState();
然而,当我点击后退按钮时,我确实想要返回上一个活动时仍然打开导航抽屉。
我知道我可以简单地设置一个onClickListener,但我认为Android有更原生的方式导航到上一个屏幕。这是我的代码:'
的onCreate:
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
isOpen = false;
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
isOpen = true;
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
ArrayList<String> drawerTitleArray = new ArrayList<>();
drawerTitleArray.add(0, "TEST");
drawerTitleArray.add(1, "TEST 1");
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, drawerTitleArray));
其他:
@Override
public boolean onOptionsItemSelected(MenuItem item){
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
答案 0 :(得分:1)
在您的onOptionsItemSelected()
抽屉活动中:
@Override
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == android.R.id.home) {
super.onBackPressed();
return true;
}
else
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}