How to make a view with rounded corners?

前端 未结 20 1257
遇见更好的自我
遇见更好的自我 2020-11-27 11:08

I am trying to make a view in android with rounded edges. The solution I found so far is to define a shape with rounded corners and use it as the background of that view.

20条回答
  •  离开以前
    2020-11-27 11:41

    With the Material Components Library the best way to make a View with rounded corners is to use the MaterialShapeDrawable.

    Create a ShapeAppearanceModel with custom rounded corners:

    ShapeAppearanceModel shapeAppearanceModelLL1 = new ShapeAppearanceModel()
            .toBuilder()
            .setAllCorners(CornerFamily.ROUNDED,radius16)
            .build();
    

    Create a MaterialShapeDrawable:

    MaterialShapeDrawable shapeDrawableLL1 = new MaterialShapeDrawable(shapeAppearanceModeLL1);
    

    If you want to apply also an elevationOverlay for the dark theme use this:

    MaterialShapeDrawable shapeDrawableLL1 = MaterialShapeDrawable.createWithElevationOverlay(this, 4.0f);
    shapeDrawableLL1.setShapeAppearanceModel(shapeAppearanceModelLL1);
    

    Optional: apply to the shapeDrawable a background color and a stroke

    shapeDrawableLL1.setFillColor(
           ContextCompat.getColorStateList(this,R.color...));
     shapeDrawableLL1.setStrokeWidth(2.0f);
     shapeDrawableLL1.setStrokeColor(
           ContextCompat.getColorStateList(this,R.color...));
    

    Finally apply the shapeDrawable as background in your LinearLayout (or other view):

    LinearLayout linearLayout1= findViewById(R.id.ll_1);
    ViewCompat.setBackground(linearLayout1,shapeDrawableLL1);
    

提交回复
热议问题