BottomNavigationView is one of the components available as part of the Material Design Components (MDC). As of version 1.3.0-alpha01 of MDC, BottomNavigationView supports a bunch of customizations like changing its background color, changing the color and size of its menu icons, etc. But one thing missing is changing its shape. It could be nice if we had the option to have a BottomNavigationView with rounded corners.
In this post, I’m going to talk about how to customize the shape of a BottomNavigationView but, before getting to that it’s good to know about
MaterialShapeDrawable and ShapeAppearanceModel
Some of the components of MDC support custom shapes. This support is provided by classes
MaterialShapeDrawable draws itself using a path generated by a
ShapeAppearanceModel is made of
EdgeTreatments that are combined to create a custom shape path.
To define a custom shape we need to define a
ShapeAppearanceModel and this is done in a layout file using the
shapeAppearance attribute. This attribute references a style that contains shape values that are used to style the component. In other words, when you set the
shapeAppearance attribute, you are defining a
ShapeAppearanceModel reads in the
shapeAppearance style and creates corner and edge treatments out of the
MaterialShapeDrawable uses this
ShapeAppearanceModel to draw the shape of the component.
Take a Button as an example. We want to set a custom shape for it. To do so, first, we define a style in styles.xml as follows:
Then we use the defined style in our layout file like this:
and the result would be like the following:
To the point!
Now it’s time to see how we can set a custom shape for a BottomNavigationView. As already mentioned, BottomNavigationView doesn’t support the
shapeAppearance attribute. So we should find a workaround for changing its shape.
If you take a look at the source code of BottomNavigationView you can see that the background of BottomNavigationView is an instance of
MaterialShapeDrawable. To access this
MaterialShapeDrawable we get the background of the BottomNavigationView, and cast it to
MaterialShapeDrawable. Now that we have the
MaterialShapeDrawable we can access it to change the shape of the BottomNavigationView.
The above code changes the shape of a BottomNavigationView to be like the following image.