Android UI: Creating a layout rounded only in the top

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="24dp">

<android.support.v7.widget.CardView
android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_margin="16dp"
app:cardCornerRadius="8dp">

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/kitty" />

</android.support.v7.widget.CardView>

</FrameLayout>

But this works only from Lollipop onwards.

From Lollipop onwards, you can clip any View to its outline. What that means is if you set a background to be a rounded shape for any View, then the View will be clipped to be rounded like in the image shared above.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="8dp" />
</shape>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="24dp">

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_margin="16dp"
android:background="@drawable/bg_rounded"
android:scaleType="centerCrop"
android:src="@drawable/kitty" />

</FrameLayout>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" />

</shape>
val image = findViewById<ImageView>(R.id.image)
val curveRadius = 20F

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

image.outlineProvider = object : ViewOutlineProvider() {

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun getOutline(view: View?, outline: Outline?) {
outline?.setRoundRect(0, 0, view!!.width, (view.height+curveRadius).toInt(), curveRadius)
}
}

image.clipToOutline = true

}

--

--

Android Engineer, Occasional Digital Nomad, Noob Dad, History Buff, Wanderlust

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sadesh

Sadesh

Android Engineer, Occasional Digital Nomad, Noob Dad, History Buff, Wanderlust