解决此问题的最简单方法是,如果您想在运行时更改诸如填充/描边颜色或描边宽度之类的小事情,则两个具有相同矢量图像的两个版本具有这种差异,例如,其中一个具有只有描边颜色,另一种填充:
ic_heart_stroked.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z"
android:strokeWidth="1"
android:strokeColor="#000" />
</vector>
ic_heart_filled.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z"/>
</vector>
然后在你的代码中,当用户点击时在两个文件之间切换:
ibWhishlist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ibWhishlist.setImageResource(R.drawable.ic_heart_filled);
}
});
另一种方法是使用其中一个现成的库。
RichPathAnimator 最好的库之一,它支持在运行时更改矢量颜色、笔划宽度甚至为矢量图形设置动画。
如何使用?
首先,将库依赖项添加到您的应用程序 build.gradle。然后在您的 vector.xml 中为您要更改的路径命名:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:name="heartPath1"
android:fillColor="#00000000"
android:pathData="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z"
android:strokeWidth="1"
android:strokeColor="#000" />
</vector>
在您的布局中将Imagebutton 替换为com.richpath.RichPathView 并在vector 属性中在该标签中传递您的矢量资源:
<com.richpath.RichPathView
android:id="@+id/heartView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:vector="@drawable/ic_heart" />
在您的Activity 中获取对richpathview 的引用,然后调用findRichPathByName(YOUR_PATH_NAME)
RichPathView heartView = findViewById(R.id.heartView);
//Providing the path name that you add to your vector,
//in our example it's 'heartPath1'.
RichPath path= heartView.findRichPathByName("heartPath1");
//Set on heart path click listener.
path.setOnPathClickListener(new RichPath.OnPathClickListener() {
@Override
public void onClick(RichPath richPath) {
//Change the path color.
richPath.setFillColor(Color.RED);
//Change stroke width to zero.
richPath.setStrokeWidth(0);
}
});
如果不想使用RichPathView 代替ImageView 或ImageButton,并且想更改矢量路径中的某些内容,请考虑使用VectorChildFinder。