Android之vector代码修改颜色

  前言:google给了很多material design icon,在开发过程中,可以下载下来直接使用,下载地址为https://materialdesignicons.com/ 。

  1.下载图标,并放入Android工程中。

  下面的这个代码就是从上面的网址下载下来的一个icon的代码,直接放在drawlable文件夹中。

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="24dp"
    android:width="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path android:fillColor="#000" android:pathData="M3,3H21V5H3V3M3,7H21V9H3V7M3,11H21V13H3V11M3,15H21V17H3V15M3,19H21V21H3V19Z" />
</vector>

  2.在activity_main.xml文件中应用引入的图标

<ImageButton
            android:id="@+id/my_tasks_button"
            style="?android:attr/buttonBarStyle"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:background="@color/window_background"
            android:src="@drawable/account"
            android:layout_gravity="center_vertical"/>

  3.在代码中使用。

  在点击的时候修改图标的颜色,在MainActivity中进行代码修改图标的颜色。

private ImageButton myTasksButton;
private Drawable myTasksDrawable;
myTasksButton = (ImageButton)findViewById(R.id.my_tasks_button);
myTasksDrawable = myTasksButton.getDrawable();

  然后在何时的位置,修改图标的颜色

myTasksDrawable.setTint(Color.BLUE);

  这样,图标就由原来的黑色变成了蓝色。

原文地址:https://www.cnblogs.com/zhangmiao14/p/6121192.html