Android create LayerDrawable programmatically example tutorial

How to use LayerDrawable inside android application that holds array of Drawables.

LayerDrawable is used to hold and manage multiple drawable using Drawable-Array. So android app developer can create/replace existing object/widget to LayerDrawable colors. So here is the complete step by step tutorial for Android create LayerDrawable programmatically example tutorial.

android-project-download-code-button

Android create LayerDrawable programmatically example tutorial.

Code for MainActivity.java file.

 package com.layerdrawable_android_examples.com;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

 //Creating Multiple ColorDrawable.
 ColorDrawable left = new ColorDrawable(Color.BLUE);
 ColorDrawable top = new ColorDrawable(Color.CYAN);
 ColorDrawable right = new ColorDrawable(Color.RED);
 ColorDrawable bottom = new ColorDrawable(Color.GREEN);
 ColorDrawable background = new ColorDrawable(Color.WHITE);
 
 Drawable[] DrawableArray = new Drawable[]{
 left,
 top,
 right,
 bottom,
 background
 };
 
 LayerDrawable layerdrawable;
 
 View view;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 view = (View)findViewById(R.id.view1);
 
 layerdrawable = new LayerDrawable(DrawableArray);
 
 layerdrawable.setLayerInset(0,0,0,18,0);

 layerdrawable.setLayerInset(1,18,0,0,18);

 layerdrawable.setLayerInset(2,18,18,0,0);

 layerdrawable.setLayerInset(3,18,18,18,0);

 layerdrawable.setLayerInset(4,18,18,18,18);
 
 view.setBackgroundDrawable(layerdrawable);
 
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.layerdrawable_android_examples.com.MainActivity" >

 <View
 android:id="@+id/view1"
 android:layout_width="100dp"
 android:layout_height="100dp"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:background="#5bc0de" />

</RelativeLayout>

Screenshot:

Android create LayerDrawable programmatically example tutorial

Click here to download Android create LayerDrawable programmatically example tutorial project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *