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?

4

3 回答 3

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.

于 2013-03-04T04:27:47.463 回答
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;
}
于 2013-03-04T04:45:07.107 回答
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.

于 2013-03-04T04:27:17.557 回答