简体   繁体   中英

How do I implement this Material Design 2.0 button shape?

I would like to achieve the button shape looking like the one in Material Components example

例子

What I already tried to do is setting custom style for the button like this

    <style name="ButtonAddLeft" parent="Widget.MaterialComponents.Button.Icon">
        <item name="backgroundTint">@color/secondary</item>
        <item name="android:textColor">@color/primary</item>
        <item name="shapeAppearance">@style/ButtonAddLeftShape</item>
    </style>

    <style name="ButtonAddLeftShape">
        <item name="cornerFamilyTopLeft">cut</item>
        <item name="cornerFamilyBottomLeft">cut</item>
        <item name="cornerSize">12dp</item>
    </style>

But this does not look like the one from the example, regardless of how I set the cornerSize.

You need to set the corner cut style to the theme.

    <style name="RightCutButton" parent="ThemeOverlay.MaterialComponents.Light">
        <item name="shapeAppearanceSmallComponent">@style/CornerCut</item>
    </style>

    <style name="CornerCut" parent="ShapeAppearance.MaterialComponents.SmallComponent">
        <item name="cornerFamilyTopRight">cut</item>
        <item name="cornerFamilyBottomRight">cut</item>
        <item name="cornerSizeTopRight">18dp</item>
        <item name="cornerSizeBottomRight">18dp</item>
    </style>

    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="shapeAppearanceSmallComponent">@style/CornerCut</item>
    </style>

You can use the app:shapeAppearanceOverlay attribute in your layout:

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

with:

  <style name="ButtomShapeArrowRight">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">4dp</item>
    <item name="cornerFamilyTopRight">cut</item>
    <item name="cornerFamilyBottomRight">cut</item>
    <item name="cornerSizeTopRight">50%</item>
    <item name="cornerSizeBottomRight">50%</item>
  </style>

在此处输入图片说明

You can also achieve it programmatically:

MaterialButton button_arrow = findViewById(R.id.button_arrow);
button_arrow.setShapeAppearanceModel(
    button_arrow.getShapeAppearanceModel()
        .toBuilder()
        .setTopLeftCorner(CornerFamily.ROUNDED,..)
        .setBottomLeftCorner(CornerFamily.ROUNDED,...)
        .setBottomRightCorner(CornerFamily.CUT, new RelativeCornerSize(0.5f))
        .setTopRightCorner(CornerFamily.CUT, new RelativeCornerSize(0.5f))
        .build()
);

Just a note about new RelativeCornerSize(0.5f) : It changed in 1.2.0-beta01 . Before it was new RelativeCornerSize(50)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM