» » Changing Android SVG graphic color programmatically

Changing Android SVG graphic color programmatically

You can use vector graphics on Android and change the graphic color with code. In this way, it is not necessary to use different graphics for each color.

The actions I wanted to do were:

- Being able to choose colors for a folder list and folder icons in the list.
- Using a single vector graphic.

Changing Android SVG graphic color programmatically

My actions:

I downloaded an icon from FontAwesome in SVG format.

Then it was necessary to transfer it to Android Studio. But the format drawable of the icon I downloaded for this process is incompatible. I used the svg2android tool to SVG convert it to the appropriate format. In this way, I converted the Site to Drawable XML format and included it in the project. SVG

In order to use it properly in Layout, I converted it to XML as src and added the folder icon that I added to the project. We can specify the color we want to give the gold as the tint . Of course, we can change this color programmatically afterwards.

I am using the layout here as ListView row. I can define a different color for the icon in each line. The name of the model I use is Folder . There is a title and color data for each folder model. The folder.getColor() in the code is the hex color code of the current folder. Example: #FF0000

We convert hex color code to int color code with color.parseColor(folder.getColor()) . Then we change the color of the graphic using the android.graphics.PorterDuff.Mode.SRC_IN mode with setColorFilter

holder.folder.setColorFilter(Color.parseColor(folder.getColor()), android.graphics.PorterDuff.Mode.SRC_IN);

Related Articles

Add Your Comment

reload, if the code cannot be seen

All comments will be moderated before being published.