Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Is there a simple way to create rounded corners for a view without having to create a separate drawable each time?

I have gone through various solutions on the internet, which enable us to create views with rounded corners. Most of them require the use of creating custom views, or to create a drawable in xml or a nine-patch each time we need a rounded corner view.

The problem is that when I implement such views, I need to create a drawable for every such view, even if two views have everything but just the background color in common. This is kind of irritating for me and I've heard the iOS framework provides a good way to create round cornered views. Any help would be much appreciated.

Edit: Along with rounded corners, the press effect of a view and shadows are also among the common styles used. Please let your solution include those effects.

like image 720
Harsha Avatar asked Nov 26 '19 08:11

Harsha


1 Answers

With the Material Components Library you can use the MaterialShapeDrawable to draw custom shapes.

For example with a TextView you can do:

    <TextView
        android:id="@+id/textview"
        android:backgroundTint="@color/secondaryColor"
        ../>

Then create a MaterialShapeDrawable:

float radius = getResources().getDimension(R.dimen.default_corner_radius);

TextView textView = findViewById(R.id.textview);
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
        .toBuilder()
        .setAllCorners(CornerFamily.ROUNDED,radius)
        .build();

MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
ViewCompat.setBackground(textView,shapeDrawable);

enter image description here

With a simple View:

<View
    android:id="@+id/line"
    android:layout_width="match_parent"
    android:layout_height="4dp"
    android:backgroundTint="@color/..."/>

Then apply the same MaterialShapeDrawable:

View line = findViewById(R.id.line);
ViewCompat.setBackground(line,shapeDrawable);

enter image description here

You can also create different corners:

ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
    .toBuilder()
    .setAllCorners(CornerFamily.ROUNDED,0)
    .setBottomRightCorner(CornerFamily.ROUNDED,radius)
    .build();

enter image description here

Also most of the components provided by the Material Component Library have a MaterialShapeDrawable as background.
In these cases just use something like (in this example a MaterialCardView).

  MaterialCardView cardView = findViewById(R.id.card);
  cardView.setShapeAppearanceModel(cardView.getShapeAppearanceModel()
        .toBuilder()
        .setBottomLeftCornerSize(...)
        .setBottomEdge(...)
        .build());

It requires the version 1.1.0 of the library. Currently 1.1.0-beta02.

like image 198
Gabriele Mariotti Avatar answered Oct 20 '22 11:10

Gabriele Mariotti