7

I want to set the rounded corners without xml. How can I do it in java code?

Button b = new Button (this);
b.set???? (??) ;

I tried to write b.setCornerRadius(3.0f), but it is undefined for button object. Thanks.

tatiana_c
  • 948
  • 7
  • 16
  • 31
  • have a look into this: http://stackoverflow.com/questions/6003382/how-can-i-work-around-android-issue-9161-where-bottomrightradius-and-bottomleft – Seshu Vinay Jan 03 '12 at 08:35

4 Answers4

31

Use GradientDrawable

GradientDrawable gdDefault = new GradientDrawable();
gdDefault.setColor(bgColor);
gdDefault.setCornerRadius(cornerRadius);
gdDefault.setStroke(strokeWidth, strokeColor);
Ndroid
  • 449
  • 4
  • 5
4

create a shape in your drawable folder and set the desired radius and set this drawable as background to your button:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="5dip"/>
        </shape>
    </item>
</layer-list>
Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • Hi Gabi, thanks for the answer. I created the xml file as you wrote, but how can I receive reference to rectangle in the code? I suppose it is something like b.setBackground(getResources().????). What I write instead of ?? – tatiana_c Jan 03 '12 at 10:22
  • you just need to get the drawable (drawable being the name of this xml) and set is as background to your button (if you do this from code) or just the background in xml the name of your xml – Buda Gavril Jan 04 '12 at 10:11
  • 3
    If the xml is named "some_drawable.xml", you can do it via the following: `b.setBackgroundResource(R.drawable.some_drawable);` – Stunner Apr 24 '13 at 22:24
0

Try setGradientRadius(). setCornerRadius() set wrong size.

GradientDrawable drawable = (GradientDrawable)image.getBackground();
drawable.setGradientRadius(radiuspx);
inhogo
  • 253
  • 3
  • 9
0

See the documentation for Shape Drawable

clemp6r
  • 3,665
  • 2
  • 26
  • 31
  • Hi Clemp6r, I saw now the link, but I still don't understand what should I write exactly. If you can to write some example or some explanation please. Thanks. – tatiana_c Jan 03 '12 at 10:31
  • The example of @gabi is right. Create an XML file like his example, and apply the resulting drawable in java using button.setBackgroundResource(R.drawable.the_drawable_name). – clemp6r Jan 03 '12 at 14:44