2

I have a Button which populates a GridView using a custom adapter's call to getView(). As such, there is no .xml file for the Button.

Is there a way to programmatically round the Button?

sdasdadas
  • 23,917
  • 20
  • 63
  • 148

3 Answers3

6

Use a nine patch, here is an example one:

enter image description here

save this in your /res/drawable-mdpi/ directory with the filename btn_round.9.png

then in your java code do this:

mBtn.setBackgroundResource(R.drawable.btn_round);

because it is 9 patch wit will stretch to fit whatever content you are putting inside the button. Search for "android draw9patch" to learn more about how to create the 9 patch files.

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
2

Below given method returns rounded bitmap of image.Apply it to button image and check if this can help

public Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
            .getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
}
Sanket Pandya
  • 1,095
  • 7
  • 21
1

Use an XML drawable background with corners and use setBackground. See How to make the corners of a button round?

You can use this even though the button itself isn't defined in xml, you're just declaring the background as an xml file.

Community
  • 1
  • 1
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127