sdasdadas
sdasdadas

Reputation: 25096

How do I round a button programmatically in Android?

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?

Upvotes: 2

Views: 2772

Answers (3)

Sanket Pandya
Sanket Pandya

Reputation: 1095

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;
}

Upvotes: 2

FoamyGuy
FoamyGuy

Reputation: 46846

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.

Upvotes: 6

Gabe Sechan
Gabe Sechan

Reputation: 93542

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.

Upvotes: 1

Related Questions