从颜色选择器获取错误的颜色值



我正在尝试向我的自定义日历视图添加彩色点。可以使用颜色选择器选择颜色,但它返回如下负颜色值,例如:"-126706"(红色(。

日历视图需要一个 int,但如果我使用颜色选择器中的颜色,则会崩溃。如果我使用"R.color.holo_red_dark",它就可以工作,但随后我不能使用不同的颜色。如果我取常量值 holo_red_dark("17170455"(,它也有效。

是否可以将负 int 颜色转换为 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;
}

这是因为颜色选取器返回颜色的十六进制表示形式(AARRGGBB 格式(,而您调用的方法需要表示资源 ID 的int。应从颜色选取器返回的值创建一个Color实例,然后将此对象传递给颜色设置器。

例如,蓝色是 -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);

,然后将其设置为事件。

最新更新