这只是一个可以改进代码的想法。
您可以更改形状FloatingActionButton
与shapeAppearanceOverlay
属性:
<com.google.android.material.floatingactionbutton.FloatingActionButton
app:shapeAppearanceOverlay="@style/cutfab"
..>
with:
<style name="cutfab">
<item name="cornerFamily">cut</item>
<item name="cornerSize">15dp</item>
</style>
然后你可以定义BottomAppBar
在你的布局中:
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottomAppBar"
app:fabAlignmentMode="center"
app:fabCradleVerticalOffset="14dp"
app:fabCradleMargin="8dp" />
最后您可以申请BottomAppBar
a TopEdgeTreatment
。就像是:
BottomAppBar bar = findViewById(R.id.bar);
BottomAppBarTopEdgeTreatment topEdge = new BottomAppBarCutCornersTopEdge(
bar.getFabCradleMargin(),
bar.getFabCradleRoundedCornerRadius(),
bar.getCradleVerticalOffset());
MaterialShapeDrawable babBackground = (MaterialShapeDrawable) bar.getBackground();
babBackground.setShapeAppearanceModel(
babBackground.getShapeAppearanceModel()
.toBuilder()
.setTopEdge(topEdge)
.build());
哪里的BottomAppBarCutCornersTopEdge
是这样的:
public class BottomAppBarCutCornersTopEdge extends BottomAppBarTopEdgeTreatment {
private final float fabMargin;
private final float cradleVerticalOffset;
BottomAppBarCutCornersTopEdge(
float fabMargin, float roundedCornerRadius, float cradleVerticalOffset) {
super(fabMargin, roundedCornerRadius, cradleVerticalOffset);
this.fabMargin = fabMargin;
this.cradleVerticalOffset = cradleVerticalOffset;
}
@Override
@SuppressWarnings("RestrictTo")
public void getEdgePath(float length, float center, float interpolation, ShapePath shapePath) {
float fabDiameter = getFabDiameter();
if (fabDiameter == 0) {
shapePath.lineTo(length, 0);
return;
}
float diamondSize = fabDiameter / 2f;
float middle = center + getHorizontalOffset();
float verticalOffsetRatio = cradleVerticalOffset / diamondSize;
if (verticalOffsetRatio >= 1.0f) {
shapePath.lineTo(length, 0);
return;
}
shapePath.lineTo(middle - (fabMargin + diamondSize), 0);
shapePath.lineTo(middle - fabDiameter/3, (diamondSize - cradleVerticalOffset + fabMargin) * interpolation);
shapePath.lineTo(middle + fabDiameter/3, (diamondSize - cradleVerticalOffset + fabMargin) * interpolation);
shapePath.lineTo(middle + (fabMargin + diamondSize), 0);
shapePath.lineTo(length, 0);
}
}
为了获得更好的结果,您应该延长CutCornerTreatment
,实施于getCornerPath
方法与中使用的路径相同BottomAppBar
并将其应用到FloatingActionButton
.