Android LayerDrawable use instance

  • 2020-06-23 01:54:49
  • OfStack

1. During the development of THE Android project, I often saw a beautiful UI interface, for example, when you clicked on an image and it was selected, a transparent image was added. To distinguish between those that are selected and those that are not. How does this work? The answer is the effect of the use of LayerDrawable. The following is the summary of LayerDrawable. Please correct me if there is anything incorrect.

2. In simple terms, LayerDrawable inherits from Drawable. Drawable is a drawable object, which may be a bitmap BitmapDrawable, a graph ShapeDrawable, or a layer LayerDrawable. Create corresponding drawable objects according to different drawing requirements.

The LayerDrawable system will draw these Drawable objects in their array order, the Drawable object with the largest index will be drawn on top, and the root element of the XML file that defines the LayerDrawable object, layer-ES21en, can contain multiple item elements.

3. The code implementation is as follows:

Method 1: XML Method:


<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >     <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_03" />
    </item>
    <item
        android:left="25dp"
        android:top="25dp">
        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_03" />
    </item>
    <item
        android:left="50dp"
        android:top="50dp">
        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_03" />
    </item> </layer-list>

Method 2: Code: ES32en. java class:


package com.scd.layerdrawabledemo; import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView; public class MainActivity extends Activity {
    private ImageView mView;     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mView = (ImageView) findViewById(R.id.imageView1);
        // Create resource objects
        Resources resources = getResources();
        // Create array objects
        Drawable[] layers = new Drawable[2];
        layers[0] = resources.getDrawable(R.drawable.ic_01);
        layers[1] = resources.getDrawable(R.drawable.ic_02);         LayerDrawable layerDrawable = new LayerDrawable(layers);
        // Set the background
        mView.setImageDrawable(layerDrawable);     }
}


Related articles: