Search code examples
androidmaterial-designandroid-navigationview

Android - Material Design - NavigationView ScrollBar and Thumb Color


Is There any way to customize the NavigationView Scroll bar and thumb color.
Right now it is reported as bug and can`t be customized.Link for bug is here

Has anyone done customization in scroll view of navigationview do share.


Solution

  • After few hours of RnD I found this solution that helps in changing thumb color dynamically not in xml

     private void navigationViewScrollThumbColor(NavigationView navigationView) {
    
        if (navigationView != null) {
            NavigationMenuView navigationMenuView = (NavigationMenuView) navigationView.getChildAt(0);
            if (navigationMenuView != null) {
                try {
                    Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
                    mScrollCacheField.setAccessible(true);
                    Object mScrollCache = mScrollCacheField.get(navigationMenuView);
    
                    Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
                    scrollBarField.setAccessible(true);
                    Object scrollBar = scrollBarField.get(mScrollCache);
    
                    Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class);
                    method.setAccessible(true);
                    method.invoke(scrollBar, getResources().getDrawable(R.drawable.color_of_your_Choice));
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
        }
    }