Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Show the video description

In this video we will learn how to create a custom button that uses XML shapes to replace the background of the default Android button.
For this we first create 3 different XML ShapeDrawables and define a background color (solid or gradient), a padding and an outer line (stroke) around the shape, which we can also make dashed. Our shape can be an oval/circle or a rectangle. In the latter case we can also add rounded corners by setting a radius on them.
Then we put these different drawables into a StateListDrawable, where we can assign different states to them, like state_enabled, state_pressed and so on.
If we want to set this custom style only on single buttons, we just use the android:background attribute on the View directly. If we want to apply it globally to all buttons in our app, we can create a custom button theme that extends Widget.AppCompat.Button and set it as the buttonStyle on our AppTheme. In this custom button theme we can also change more attributes, like the textColor or textAppearance of our button. Optionally we can deactivate the default StateListAnimator by setting android:stateListAnimator to @null to disable the shadow and animation of the default Lollipop AppCompatButton.

button_default.xmlbutton_pressed.xmlbutton_disabled.xmlcustom_button.xmlactivity_main.xmlMainActivity.javastyles.xml