我正在尝试向我的自定义日历 View 添加彩色点。 可以使用颜色选择器选择颜色,但它会返回负颜色值,例如:“-126706”(红色)。
Calendarview 需要一个 int,但如果我使用颜色选择器中的颜色,则会崩溃。如果我使用“R.color.holo_red_dark”,它会起作用,但我不能使用不同的颜色。如果我采用 Holo_red_dark("17170455") 的常量值,它也有效。
是否可以将负整数颜色转换为像holo_red_dark的常量值这样的格式?
dot_color = colorPicker_value;
calendarView.setEventDataProvider(new FlexibleCalendarView.EventDataProvider() {
@Override
public List<? extends Event> getEventsForTheDay(int year, int month, int day) {
if (year == year_i && month == month_i_2 && day == today_i) {
List<CustomEvent> colorLst1 = new ArrayList<>();
if (dot_color != 0) {
colorLst1.add(new CustomEvent(dot_color));
}
return colorLst1;
}
return null;
}
});
return rootView;
}
最佳答案
这是因为颜色选择器返回颜色的十六进制表示形式(AARRGBB 格式),而您调用的方法需要一个表示资源 ID 的 int
。您应该根据颜色选择器返回的值创建一个 Color
实例,然后将此对象传递给颜色 setter 。
例如蓝色是-16776961(即0xff0000ff)。
编辑:
调查FlexibleCalendar的源代码后库中,我来到了这个方法(来自类com.p_v.flexiblecalendar.view.CircularEventCellView
):
@Override
public void setEvents(List<? extends Event> colorList){
if(colorList!=null){
paintList = new ArrayList<>(colorList.size());
for(Event e: colorList){
Paint eventPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
eventPaint.setStyle(Paint.Style.FILL);
eventPaint.setColor(getContext().getResources().getColor(e.getColor()));
paintList.add(eventPaint);
}
invalidate();
requestLayout();
}
}
如您所见,int
值被解释为资源标识符(即它尝试从 res
文件夹获取颜色),而不是 ARGB 值。
要解决此问题,您需要对 CircularEventCellView 进行子类化,以便使用类似于以下内容的方法覆盖 setEvents
方法:
@Override
public void setEvents(List<? extends Event> colorList){
if(colorList!=null){
paintList = new ArrayList<>(colorList.size());
for(Event e: colorList){
Paint eventPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
eventPaint.setStyle(Paint.Style.FILL);
eventPaint.setColor(e.getColor()); // ONLY THIS LINE CHANGED
paintList.add(eventPaint);
}
invalidate();
requestLayout();
}
}
修改后,如果您仍想使用资源标识符,则应通过以下代码手动检索其 ARGB 值:
int desiredColor = getContext().getResources().getColor(R.color.mycolor);
然后将其设置为事件。
关于java - 从颜色选择器获取错误的颜色值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336765/