Sin*_*ged 16 android toolbar android-actionbar navigation-drawer hamburger-menu
我想突出我的抽屉图标Toolbar(制作教程).为此,我需要它的立场.如何获得抽屉导航图标(汉堡包)视图的参考?
Nik*_*ski 23
您可以使用视图的内容描述,然后使用findViewWithText()方法获取视图参考
public static View getToolbarNavigationIcon(Toolbar toolbar){
//check if contentDescription previously was set
boolean hadContentDescription = !TextUtils.isEmpty(toolbar.getNavigationContentDescription());
String contentDescription = hadContentDescription ? toolbar.getNavigationContentDescription() : "navigationIcon";
toolbar.setNavigationContentDescription(contentDescription);
ArrayList<View> potentialViews = new ArrayList<View>();
//find the view based on it's content description, set programatically or with android:contentDescription
toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
//Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
View navIcon = null;
if(potentialViews.size() > 0){
navIcon = potentialViews.get(0); //navigation icon is ImageButton
}
//Clear content description if not previously present
if(!hadContentDescription)
toolbar.setNavigationContentDescription(null);
return navIcon;
}
Run Code Online (Sandbox Code Playgroud)
在调试模式下查看工具栏的子视图后,我看到可以在那里找到抽屉图标,作为ImageButton.(感谢Elltz)
我使用带有2个子节点的自定义xml布局的工具栏(LinearLayout和ImageView),所以我的工具栏最后有4个孩子,这些位置:
[0] LinearLayout(from custom xml)
[1] ImageView(from custom xml)
[2] ImageButton(drawer icon)
[3] ActionMenuView(menu icon)
Run Code Online (Sandbox Code Playgroud)
知道了这一点,我现在可以使用:
View drawerIcon = toolbar.getChildAt(2);
Run Code Online (Sandbox Code Playgroud)
获取对抽屉菜单图标的引用.在我的例子中,位置是2.此位置应该等于自定义工具栏布局中的子视图的数量.
如果有人找到更好的解决方案,请告诉我.
小智 5
如果您只想Drawable表示工具栏导航图标,则可以执行以下操作:
Drawable d = mToolbar.getNavigationIcon();
Run Code Online (Sandbox Code Playgroud)
您可以通过如下方法获得对用于工具栏导航图标的ImageButton的引用:
public ImageButton getToolbarNavigationButton() {
int size = mToolbar.getChildCount();
for (int i = 0; i < size; i++) {
View child = mToolbar.getChildAt(i);
if (child instanceof ImageButton) {
ImageButton btn = (ImageButton) child;
if (btn.getDrawable() == mToolbar.getNavigationIcon()) {
return btn;
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)