Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

android - How to make buttons rounded with Material Design Theming?

I want my button to have rounded corners like:

Rounded Button // Image taken from google

To achieve this with material theming in android is to set the: shapeAppearanceSmallComponent to have a rounded corner.

But setting shapeAppearanceSmallComponent also affects all other components such as EditText so now they are rounded as well.

So instead of setting it to shapeAppearanceSmallComponent, I created a shapeMaterialOverlay. Set this overlay to a buttonStyle and set this button style in the theme as the default button style.

It works but only for default buttons. If I needed a TextButton as such:

<Button
    ...
    style="@style/Widget.MaterialComponents.Button.TextButton"/>

The TextButton won't be rouned. So as a workaround, I created MyTextButton style which extends from TextButton and set the shapeOverlay there as well.

so Now if I need a TextButton, I'll do:

<Button
    ...
    style="@style/Widget.MaterialComponents.Button.MyTextButton"/>

instead.

I will have to do this for all other button types. I was wondering whether this approach is correct and if not, can anyone guide me on how to properly do this?

Thank you very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just use the app:shapeAppearanceOverlay attribute in the layout.

<com.google.android.material.button.MaterialButton
        app:shapeAppearanceOverlay="@style/buttomShape"
        .../>

with:

  <style name="buttomShape">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
  </style>

enter image description here

The only way to apply it to all buttons is to define custom styles for all the button styles as you are just doing. Something like:

  <style name="...." parent="Widget.MaterialComponents.Button">
    <item name="shapeAppearance">@style/buttomShape</item>
  </style>

  <style name="..."  parent="Widget.MaterialComponents.Button.TextButton">
    <item name="shapeAppearance">@style/buttomShape</item>
  </style>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...