13

I am trying to programmatically create a layer-list with resized bitmaps as items. From what I have seen BitmapDrawable has been deprecated. The new constructor requires the following parameters - public BitmapDrawable (Resources res, Bitmap bitmap). I have started out with a very basic example below.

    BitmapDrawable background = new BitmapDrawable();
    background.setBounds(10,10,10,10);
    Drawable[] layers = {background};
    LayerDrawable splash_test = new LayerDrawable(layers);
    splash_test.setLayerInset(0, 0, 0, 0, 0);

How would I correctly use the new BitmapDrawable constructor and how do I link a drawable resource to the background object.

Cœur
  • 37,241
  • 25
  • 195
  • 267
the_big_blackbox
  • 1,056
  • 2
  • 15
  • 35

1 Answers1

24

You mentioned that you want to make a layer list from a couple of bitmaps. What you have is largely correct, all you need to do is take each bitmap object and turn it into a BitmapDrawable. To do this you can use:

BitmapDrawable layer1 = new BitmapDrawable(context.getResources(), bitmap1);

If you are in an activity when you do this you don't even need to call context.getResources(), just getResources().

Then you will take all your layers and create your LayerDrawable, much like you already are:

Drawable[] layers = {layer1, layer2, layer3};
LayerDrawable splash_test = new LayerDrawable(layers);

(note that layer3 will be above layer2 and layer2 will be above layer1).

Once you have the LayerDrawable you can set it on the background of your view using view.setBackgoundDrawable(drawable) (on API 16 and greater) or view.setBackground(drawable) (on pre API 16). This post shows how to check the device version and call the appropriate method if you are supporting pre 16 devices.

If you want to position the layers relative to each other then you will also need to use setLayerInset() as you have in your code, but I would recommend that you try that after getting your layer-list to display.

Community
  • 1
  • 1
Dr. Nitpick
  • 1,662
  • 1
  • 12
  • 16
  • thanks so much for the detailed well written detailed explanation, what does bitmap1 above refer to or how would I create that object – the_big_blackbox Jul 02 '16 at 08:57
  • No problem! `bitmap1` is supposed to be one of the bitmaps that you want to resize and put in the layer-list. I had assumed from your question that you already had the bitmaps. If this isn't the case could you add the code where you want to do this and an explanation of where you were planning to get the bitmaps? – Dr. Nitpick Jul 02 '16 at 16:05