我一直在尝试为现有的应用程序创建一个导航抽屉。我已经找到了一些教程,但其中大多数(包括官方Android指南)似乎是为v4 ActionBarDrawerToggle库,这已被弃用。我试图使用v7库代替,但我的ActionBarDrawerToggle似乎不做什么文档说它应该做的。
编辑:根据下面的答案修改了我的代码。汉堡图标现在可以正确地来回切换,但当用户点击硬件返回按钮返回到应用的主要部分时,汉堡图标就完全消失了。为什么会发生这种情况?private void addDrawerItems() {
String[] itemArray = {"About", "Nearby", "Settings", "Feedback",};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("ContributionsActivity", "Item " + position + " selected");
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.title_activity_contributions);
setContentView(R.layout.activity_contributions);
//Set up navigation drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
addDrawerItems();
setupDrawer();
...
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// enabling drawer toggle by clicking on the app icon.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
switch (item.getItemId()) {
case android.R.id.home:
if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
你缺少同步状态,添加它,一切都会好的。