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

5
  • 3
    don't really get what you are trying to ask here Commented Sep 3, 2012 at 7:55
  • stackoverflow.com/q/5079868/543711 Commented Sep 3, 2012 at 7:58
  • I need to change Button's background in run-time. The background is 9Patch. When I do so, I see that 9Patch doesn't work as it should Commented Sep 3, 2012 at 8:01
  • Check if your 9patch is correct. Did you do it with draw9patch? Commented Sep 3, 2012 at 8:21
  • In what way does it not "work as it should"? Can you edit your question and put your patch 9 in there? Commented Sep 13, 2012 at 15:47

1 Answer 1

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)); 
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Saved me a lot of time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.