Search code examples
javaandroidandroid-drawablematerial-components-androidmaterial-components

Creating a triangle shape at the bottom of layout


I'm working on an android application that contains a shape at the top of the activity and I'm trying to implement it but struggling to do it. the shape in the green color

I have tried to create a drawable file that create a triangle shape and sets up the bottom corner radius to match the shape above but not working. anyone can help me, please.


Solution

  • You can use the EdgeTreatment included in the official Material Components Library.

    Just extend the EdgeTreatment with something like:

    public class MyTriangleEdge extends EdgeTreatment {
    
      private final float size;
      private final boolean inside;
    
      public MyTriangleEdge(float size, boolean inside) {
        this.size = size;
        this.inside = inside;
      }
    
      @Override
      public void getEdgePath(
          float length, float center, float interpolation, @NonNull ShapePath shapePath) {
        shapePath.lineTo(0, 0);
        shapePath.lineTo(center, inside ? size  : -size );
        shapePath.lineTo(length, 0);
      }
    

    and then apply it:

    MyTriangleEdge edgeTreatment = new MyTriangleEdge(height,false);
    
    LinearLayout linearLayout= findViewById(R.id.xxxx);
    ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
        .toBuilder()
        .setBottomEdge(edgeTreatment)
        .build();
    
    MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
    
    ViewCompat.setBackground(linearLayout,shapeDrawable);
    

    enter image description here

    Also for edge treatments, the parent view must disable clipping of children by setting android:clipChildren="false" in xml.