Toolbar Logo ID

I am interested in setting and adjusting various properties of the toolbar logo, for example, installing an Onclick listener or using Picasso to download and set a rounded image using the “fit” picasso method.

To do this, I need the toolbar logo identifier (take care the logo, not the navigation icon, which is android.R.id.home) to find the view, because tollbar has no way to get an ImageView.

+4
source share
1 answer

It seems that the class Toolbardynamically creates a child View, so I believe that we will have to look for the logo Viewourselves. After you have installed the logo, but before adding any other (if this is true) the logo is the only ImageViewchild element Toolbarthat we can do this:

private ImageView getLogoView(Toolbar toolbar) {
    for (int i = 0; i < toolbar.getChildCount(); i++)
        if(toolbar.getChildAt(i) instanceof ImageView)
            return (ImageView) toolbar.getChildAt(i);

    return null;
}

Another possibility is to use reflection in the classroom Toolbar. This method can be used at any time after installing the logo.

private ImageView getLogoView(Toolbar toolbar) {
    try {
        Class<?> toolbarClass = Toolbar.class;
        Field logoViewField = toolbarClass.getDeclaredField("mLogoView");
        logoViewField.setAccessible(true);
        ImageView logoView = (ImageView) logoViewField.get(toolbar);

        return logoView;
    }
    catch (NoSuchFieldException | IllegalAccessException e) {
        e.printStackTrace();
    }

    return null;
}
+6
source

Source: https://habr.com/ru/post/1570017/


All Articles