Merge circle with an icon on Android

3

To create a circular icon based on the vector icons of Android Studio, I do the following:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorAccent"/>
        </shape>
    </item>
    <item
        android:drawable="@drawable/ic_select"
        android:bottom="20dp"
        android:left="20dp"
        android:right="20dp"
        android:top="20dp"/>
</layer-list>

The result is:

That's what I want to do in a dynamic and customizable way:

  • Allow to change the color of the circle
  • Assign an icon
  • Tint of the icon

More or less reproduce the new style of Android P on the screen set, which leaves the icon in a circle.

I had thought of creating a Bitmap filled in a color, insert the icon in the middle and then with the library glide4 transform into format ciruclar with circleCropTransform , but I would like not to depend on glide and if it can be done only with java and the layers-xml

    
asked by Webserveis 16.03.2018 в 11:17
source

1 answer

2

You can also use a shape as a background and you can change the color of the programmatically.

Set a "shape" as a background:

android:background="@drawable/myRoundBackground"

To change the color, you get the current "background" of the view, you get what type of instance it is, in this case it would always be GradientDrawable , and you proceed to configure the color.

Drawable background = imageView.getBackground();    

if (background instanceof ShapeDrawable) {   
    ShapeDrawable shapeDrawable = (ShapeDrawable) background;
    shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.myColor));
} else if (background instanceof GradientDrawable) {
    GradientDrawable gradientDrawable = (GradientDrawable) background;
    gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.myColor));
} else if (background instanceof ColorDrawable) {
    ColorDrawable colorDrawable = (ColorDrawable) background;
    colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.myColor));
}

The image can be defined as foreground , programmatically or directly in the view:

  android:foreground="@drawable/ic_image"

in this way you change the background color of your image.

    
answered by 16.03.2018 / 11:43
source