我正在尝试使用以下代码在地图的折线上设置红色:

PolylineOptions rectOptions = new PolylineOptions();
rectOptions.color(R.color.colorPrimary);
String[][] lineInformation = ((MyApplication)getApplication()).getLineInformation(line);
for (int i=0; i<lineInformation.length; i++){
    rectOptions.add(new LatLng(Double.parseDouble(lineInformation[i][0]),Double.parseDouble(lineInformation[i][1])));
}


但是它不起作用,没有显示我的应用程序的primaryColour红色,而是显示了带有某些Alpha的深色。

我遵循了官方指南:https://developers.google.com/maps/documentation/android-api/shapes

最佳答案

您的问题是由颜色资源标识符和颜色值(两者均为int)之间的混淆引起的。

让我们看一下the documentation for PolylineOptions.color()


  public PolylineOptions color (int color)
  
  将折线的颜色设置为32位ARGB颜色。默认颜色是黑色(0xff000000)。


由于文档指出输入应为“ 32位ARGB颜色”,因此您不能仅传递颜色资源ID。您必须先手动将其解析为颜色值。

R.color.colorPrimary是具有一些自动生成的值的int,也许是0x7f050042之类的东西。不幸的是,这可以解释为ARGB颜色,并且会是部分透明的极深蓝色。因此,应用程序不会崩溃,您只会在折线上得到意外的颜色。

要获得正确的颜色,请使用ContextCompat.getColor()将您的颜色资源ID解析为一个颜色值,然后将该颜色值传递给color()方法:

Context c = /* some context here */
int colorPrimary = ContextCompat.getColor(c, R.color.colorPrimary);
rectOptions.color(colorPrimary);

08-18 18:47
查看更多