Home » Android » java – programmatically create layer-list

java – programmatically create layer-list

Posted by: admin June 15, 2020 Leave a comment


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();
    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.

How to&Answers:

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.