Tint bitmap in layer-list Tint bitmap in layer-list android android

Tint bitmap in layer-list


For anyone else that may come across this question. This is what I did.

Setup

  • Android Studio 2.3.2
  • Windows 10

    Gradle

  • minSdkVersion 15

  • targetSdkVersion 25
  • compile 'com.android.support:appcompat-v7:25.3.1'

Test Devices

  • Asus Padfone X Android v4.4.2
  • Samsung Galaxy S3 Android v6.0
  • Samsung Galaxy S7 Android v7.0

Layer DrawableI added android:id=@+id/bitmapID to the item containing the bitmap

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >    <item>        <shape android:shape="oval">            <solid android:color="#9e9e9e" />            <size android:width="45dp" android:height="45dp"/>        </shape>    </item>    <item        android:id="@+id/tintDrawableImg"        android:left="5dp"        android:right="5dp"        android:top="5dp"        android:bottom="5dp">        <bitmap android:src="@mipmap/ic_pencil" android:tint="#860000"   />    </item></layer-list>

Activity LayoutI added the layer drawable to an ImageView

<ImageView    android:id="@+id/tintLayerTest"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerInParent="true"    android:src="@drawable/test_layer"/>

MainActivityIn the onCreate() method we can locate the bitmap from the layer drawableusing findViewByID

public class MainActivity extends AppCompatActivity {    ImageView iv;    LayerDrawable ld;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //Declare ImageView containing LayerDrawable        iv = (ImageView)findViewById(R.id.tintLayerTest);        //Get LayerDrawable from ImageView        ld = (LayerDrawable)iv.getDrawable();        //Get specific Drawable/Bitmap from within LayerDrawable        //by ID and pass it as an independent Drawable        Drawable ldDrawable = ld.findDrawableByLayerId(R.id.tintDrawableImg);        //Pass your new Drawable to DrawableCompat.setTint        //and define your color int        DrawableCompat.setTint(ldDrawable, ContextCompat.getColor(this, R.color.colorAccent));    }}

I hope this helps others that come across this question.


Try with xml drawable using bitmap tag

Save the following file xml custom_image.xml & replace your icon & tint color

<?xml version="1.0" encoding="utf-8"?>    <bitmap      xmlns:android="http://schemas.android.com/apk/res/android"      android:src="@drawable/iv_veg"      android:tint="@color/red"> </bitmap>


As it was mentioned by @lucidbrot in the comments, android:tint should work now without any hacks.