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.
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);
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);
You can also create different corners:
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,0)
.setBottomRightCorner(CornerFamily.ROUNDED,radius)
.build();
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With