How to Create a Custom Button (With XML ShapeDrawables) in Android Studio

21
11



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.

Example code:

____________________
❗ Subscribe to the channel:

⏯ Watch more tutorials:

⭐ Become a channel member for exclusive tutorials and other perks:

㊙ Help translating the videos:

💚 Support the content:

💬 Join the Discord chat:

🎧 Audiobooks and podcasts for programmers:

👶 How to get started with Android development:

📣 Follow Coding in Flow on social media:

Facebook:

Instagram:

Twitter:

Blog:

Nguồn:https://wijstaanvooronzegrondrechten.org/

21 COMMENTS

  1. thank you from Brazil for the tutorial man. if you can help me, I need the button to change image and stay until it clicks again. Thanks

  2. i just wanted to ask that is making switch necessary because I just wanted custom button in XML … and the functionality we set it by OnClick listner on button

  3. Thanks master
    I really love your tutorials
    I wish one day seeing you making some courses in some programming languages
    Good luck

  4. everytime I look for something specific, I find one of your video with an example. Big thanks again!!. You are my hero!

  5. Thank you a lot of, I was looking for a video about this, and you are the only one who explained this so idilly

  6. Hello – Works well with button but it overrides my application's other Imagebutton style as well. How to limit the style to only desired Button?

LEAVE A REPLY

Please enter your comment!
Please enter your name here