how to make a capsule shape Button in android?
finally I found the way to do it with xml file. here is the code of the xml file that gave me the capsule shape button.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:radius="60dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#CFCFCF" />
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<size
android:height="60dp"
android:width="270dp" />
</shape>
Just use a MaterialButton
using the cornerRadius
attribute and your favorite width.
<com.google.android.material.button.MaterialButton
android:layout_width="100dp"
android:layout_height="wrap_content"
app:cornerRadius="18dp"
android:text="BUTTON"
/>
You can also use the shapeAppearanceOverlay
attribute:
<com.google.android.material.button.MaterialButton
app:shapeAppearanceOverlay="@style/buttomShape"
.../>
with:
<style name="buttomShape">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
I haven't tried all of the answers here, but I believe some/all of them are works.
The accepted answer is also works, but it can be simplified. Since I love elegant and simple solution, I come up with my own solution. Basically, we just need to add radius big enough compared with your View
width and height, so it will create a round corner. In this case I put 1000dp
to make it safe. We don't even need to add android:shape="rectangle"
at all.
Just follow these 2 simple steps:
Create an XML file in your drawable folder. For example let's name it
bg.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="1000dp"/> <solid android:color="@color/yourPreferredColor"/> </shape>
Then you can use it in layout XML file as your
View
propertyandroid:background="@drawable/bg"
or directly in the codeview.setBackgroundResource(R.drawable.bg)