4

does anyone have tried to set 9Patch background of button dynamically? If it is important, button's width and height is set wrap_content

If yes, how have you solved the "black line" issue?

Thanks

Toochka
  • 894
  • 1
  • 9
  • 25

1 Answers1

5

If you are seeing the black dots you drew on the 9-patch image, it's because you have not pre-compiled your images.

To set 9-patch images as background at runtime, they have to be previously compiled, when the border is removed and encoded to a PNG chunk.

You can do that by inserting the .9.png images in the res/drawable folder of your application, compiling it and generating the .apk (on Eclipse, right click on your project root > Android Tools > Export Unsigned Application Package). Then unzip the .apk and you'll have the .9.png images with the 9-patch compiled data in them.

With your pre-compiled 9-patch images, do something like that to load your image:

private Drawable loadNinePatch(String path, Context context) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        byte[] chunk = bitmap.getNinePatchChunk();
        if(NinePatch.isNinePatchChunk(chunk)) {
            return new NinePatchDrawable(context.getResources(), bitmap, chunk, new Rect(), null);
        } else return new BitmapDrawable(bitmap);
}

and then set it as the background of your button:

button.setBackgroundDrawable(loadNinePatch("/data/data/your.app/files/button_background.9.png", context));
brnunes
  • 1,943
  • 26
  • 30