ihaydinn
ihaydinn

Reputation: 197

How to fix programmatically round corners buttons on android?

I am going to want to rounded corners on button like this below code

        button.setWidth(buttonWidth);
        button.setHeight(buttonHeight);

How to define rounded buttons with java code, no xml

Upvotes: 4

Views: 3426

Answers (4)

user18271507
user18271507

Reputation:

Just set your theme to MaterialComponents. Note that this will mess up your current theme though.

https://learntodroid.com/how-to-create-rounded-corners-for-a-button-in-android/ may be another option.

Upvotes: 0

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363439

Use the Material Components for Android.

Just add the dependency:

implementation ‘com.google.android.material:material:1.0.0’

Add the MaterialButton in your layout:

<com.google.android.material.button.MaterialButton
   ....
   style="@style/Widget.MaterialComponents.Button.OutlinedButton"
   app:cornerRadius=".."
   app:strokeColor="@color/colorPrimary"/>

and use the method setCornerRadius.
Something like:

button.setCornerRadius(..);

Upvotes: 3

Payam Asefi
Payam Asefi

Reputation: 2757

First create a background:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
    <shape android:shape="rectangle"  >
        <corners android:radius="3dip" />
        <stroke android:width="1dip" android:color="#5e7974" />
        <gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92"  />            
    </shape>
</item>
<item android:state_focused="true">
    <shape android:shape="rectangle"  >
        <corners android:radius="3dip" />
        <stroke android:width="1dip" android:color="#5e7974" />
        <solid android:color="#58857e"/>       
    </shape>
</item>  
<item >
   <shape android:shape="rectangle"  >
        <corners android:radius="3dip" />
        <stroke android:width="1dip" android:color="#5e7974" />
        <gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />            
   </shape>
</item>

and then:

button.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));

this answer is based on this and this link.

Upvotes: -1

Gabe Sechan
Gabe Sechan

Reputation: 93542

You'd make an xml drawable with the rounded rect background you want (make sure to use a state list drawable if you want it to hilight when pressed) and set it as the background. Setting it as the background is just a setBackgroundDrawable call.

Upvotes: 0

Related Questions