我正在使用android.support.v7.app.ActionBarActivity
中的操作栏,因此我的活动声明如下:
public class MyActivity extends ActionBarActivity {
我正在阅读教程,其中展示了如何添加抽屉:
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close);
这是针对import android.support.v4.app.ActionBarDrawerToggle
的。现在我已经决定使用v7
,因为v4
已被弃用,但v7
的构造函数不接受抽屉的图标。我用google搜索,发现解决方案是使用接受toolbar
的构造函数风格:
ActionBarDrawerToggle(this, drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
但我没有使用工具栏。所以我不明白如何在没有工具栏的情况下使用v7
设置图标。我应该切换到使用工具栏吗?
答案 0 :(得分:5)
嘿,你在这里得到解决方案..
private Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
这个也是一个很好的方法,我亲自使用这个。
public class MyActionBarDrawerToggle extends android.support.v7.app.ActionBarDrawerToggle {
public MyActionBarDrawerToggle(Activity activity, final DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
setHomeAsUpIndicator(R.drawable.drawer_toggle);
setDrawerIndicatorEnabled(false);
setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.LEFT);
}
});
}
}
谢谢。