Get reference to drawer toggle in support actionbar

前端 未结 2 778
臣服心动
臣服心动 2020-12-01 23:44

I use ShowcaseView library for app tutorial. I need to get a reference to Navigation Drawer toggle button(aka \"burger button\"):

相关标签:
2条回答
  • 2020-12-02 00:31

    In your Xml file just add a view in leftmost of toolbar/Layout, and use this view in your showcase target

    0 讨论(0)
  • 2020-12-02 00:32

    In the original ActionBar, the two Views commonly shown on the left are the Up View and the Home View. The Up View is the button that usually displays the "hamburger" icon, while the Home View displays the app icon. Things have changed with the Toolbar class. There is no longer a default View with the android.R.id.home ID, though setting a Toolbar as the support ActionBar will still fire the onOptionsItemSelected() with the appropriate item ID when the View in question is clicked.

    The current Toolbar class now refers to the Up View internally as the Nav Button View, and it creates that View dynamically. I've used two different methods to get a reference to that - one that iterates over a Toolbar's child Views, and one that uses reflection on the Toolbarclass.

    For the iterative method, after you've set the toggle, but before you've added any other ImageButtons to the Toolbar, the Nav Button View is the only ImageButton child of the Toolbar, which you can get like so:

    private ImageButton getNavButtonView(Toolbar toolbar)
    {
        for (int i = 0; i < toolbar.getChildCount(); i++)
            if(toolbar.getChildAt(i) instanceof ImageButton)
                return (ImageButton) toolbar.getChildAt(i);
    
        return null;
    }
    

    If you need a reference to the app icon's View - that which corresponds to the old Home View - you can use a similar method looking for an ImageView.

    The reflective method, on the other hand, can be used at any time after the View has been set on the Toolbar.

    private ImageButton getNavButtonView(Toolbar toolbar) {
        try {
            Class<?> toolbarClass = Toolbar.class;
            Field navButtonField = toolbarClass.getDeclaredField("mNavButtonView");
            navButtonField.setAccessible(true);
            ImageButton navButtonView = (ImageButton) navButtonField.get(toolbar);
    
            return navButtonView;
        }
        catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    
        return null;
    }
    

    Again, a similar method can be used for the icon View, retrieving instead the "mLogoView" Field.

    0 讨论(0)
提交回复
热议问题