如何更改 MaterialCalendarView 中日历日期的背景颜色

Posted

技术标签:

【中文标题】如何更改 MaterialCalendarView 中日历日期的背景颜色【英文标题】:How do I change the background color of calendar dates in MaterialCalendarView 【发布时间】:2017-05-05 08:38:00 【问题描述】:

我正在尝试使用收到的 JSON 响应更改日期的背景颜色。但我遇到了一些困难。

这是我的代码:

<com.prolificinteractive.materialcalendarview.MaterialCalendarView
            android:id="@+id/calendarView"
            android:layout_
            android:layout_
            android:layout_marginBottom="16dp"
            android:layout_marginTop="16dp" />

MainActivty.java

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener      

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        calbg();
        materialCalendarView.setDateTextAppearance(View.ACCESSIBILITY_LIVE_REGION_ASSERTIVE);
        Calendar calendar = Calendar.getInstance();
        materialCalendarView.setSelectedDate(calendar.getTime());
        materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener()   
        get1 = sharedpreferences.getString(CLIENT, "");       
        materialCalendarView.setDateTextAppearance(getTitleColor());            
        materialCalendarView.setHeaderTextAppearance(R.style.AppTheme_Dark1);   
    

    private void calbg() 
        // Volley's json array request object
        StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
                new Response.Listener < String > ()   
                    @Override
                    public void onResponse(String response) 
                        JSONObject object = null;
                        try 
                            object = new JSONObject(response);
                         catch (JSONException e) 
                            e.printStackTrace();
                        

                        JSONArray jsonarray = null;
                        try 
                            jsonarray = object.getJSONArray("Table");
                         catch (JSONException e) 
                            e.printStackTrace();
                        

//                        SimpleDateFormatter formatter = new SimpleDateFormatter(); //TODO: update this line with the correct formatter
                        List<Event> events = new ArrayList<>();
                        for (int i = 0; i < jsonarray.length(); i++) 
                            try 
                                JSONObject obj = jsonarray.getJSONObject(i);

                                String str = obj.getString("eventdate").replaceAll("\\D+","");
                                String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
                                DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                                timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));

                                Date time = new java.util.Date(Long.parseLong(upToNCharacters));
//                                System.out.println(time);
//                                movie.setDate(String.valueOf(timeZoneFormat.format(time)));
//                                String str2 = String.valueOf(timeZoneFormat.format(time));
                                String str1 = obj.optString("eventcolor");
//                                Date date = formatter.parse(str2);
                                int color = Integer.parseInt(str1); //TODO: update this line with the correct code to parse your color
                                Event event = new Event(time, color);
                                events.add(event);
                            
                            catch (JSONException e) 
                                e.printStackTrace();
                            
                        

                        for (Event event : events) 

                        //Here is the problem in parameter
                            EventDecorator eventDecorator = new EventDecorator(event.getDate(), event.getColor()); 
                            materialCalendarView.addDecorator(eventDecorator);
                        
                    

                , new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error) 
                //                VolleyLog.d(TAG, "Error: " + error.getMessage());
                //                hidePDialog();

            
        ) 
            @Override
            protected Map < String, String > getParams() 
                Map < String, String > params = new HashMap < String, String > ();
                params.put(CLIENT, get1);
                return params;
            
        ;
        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    

JSON 响应

  
   "Table":[  
        
         "userid":4,
         "eventname":"adi",
         "eventdate":"\/Date(1484121600000-0800)\/",
         "eventcolor":"2413AD",
         "autoid":2005
      ,


        
         "userid":4,
         "eventname":"Mandeep",
         "eventdate":"\/Date(1480924800000-0800)\/",
         "eventcolor":"3A87AD",
         "autoid":2002
      ,
        
         "userid":4,
         "eventname":"nefv",
         "eventdate":"\/Date(1477465200000-0700)\/",
         "eventcolor":"39AD37",
         "autoid":2
      ,

   ]
  

【问题讨论】:

您能否添加图像,说明它现在在布局中的外观以及您想要的外观? 目前看起来像这样,我想更改活动日期的背面@Flummox 【参考方案1】:

第一步是创建一个DayViewDecorator,它将以Date 和颜色作为参数:

public class EventDecorator implements DayViewDecorator 

    private final Drawable drawable;
    private final CalendarDay day;
    private final int color;

    public EventDecorator(MaterialCalendarView view, Date date, int color) 
        this.day = CalendarDay.from(date);
        this.color = color;
        this.drawable = createTintedDrawable(view.getContext(), color);
    

    @Override
    public boolean shouldDecorate(CalendarDay day) 
        if (this.day.equals(day)) 
            return true;
        
        return false;
    

    @Override
    public void decorate(DayViewFacade view) 
        view.setSelectionDrawable(drawable);
    

    private static Drawable createTintedDrawable(Context context, int color) 
        return applyTint(createBaseDrawable(context), color);
    

    private static Drawable applyTint(Drawable drawable, int color) 
        Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(wrappedDrawable, color);
        return wrappedDrawable;
    

    private static Drawable createBaseDrawable(Context context) 
        return ContextCompat.getDrawable(context, R.drawable.day);
    

(注意,我使用this answer 中的代码来应用着色。另外,由于您没有指定,我假设可绘制对象是某种需要以这种方式着色的图像。)

下一步是创建一个Event 类,用于存储您从 API 调用解析的事件:

public class Event 

    private Date date;
    private int color;

    public Event(Date date, int color) 
        this.date = date;
        this.color = color;
    

    public Date getDate() 
        return date;
    

    public int getColor() 
        return color;
    

现在我们需要为您的 onResponse() 方法添加逻辑来解析 JSON 并为每个事件添加装饰器。很难知道具体要写什么,因为您没有给出 JSON 的样本。您之前的问题表明您已经知道如何解析Date,所以我认为这就足够了。既然你没有具体说明,那我就先不说了吧。另外,我只是附加到您的代码 - 我不会尝试重构它。

@Override
public void onResponse(String response) 
    JSONObject object = null;
    try 
        object = new JSONObject(response);
     catch (JSONException e) 
        e.printStackTrace();
    

    JSONArray jsonarray = null;
    try 
        jsonarray = object.getJSONArray("Table");
     catch (JSONException e) 
        e.printStackTrace();
    

    SimpleDateFormatter formatter = new SimpleDateFormatter(); //TODO: update this line with the correct formatter
    List<Event> events = new ArrayList<>();
    for (int i = 0; i < jsonarray.length(); i++) 
        try 
            JSONObject obj = jsonarray.getJSONObject(i);
            String str2 = obj.optString("eventdate");
            String str1 = obj.optString("eventcolor"); 
            Date date = formatter.parse(str2);
            int color = Integer.parseInt(str1); //TODO: update this line with the correct code to parse your color
            Event event = new Event(date, color);
            events.add(event);
        
        catch (JSONException e) 
            e.printStackTrace();
        
    

    for (Event event : events) 
        EventDecorator eventDecorator = new EventDecorator(calendarView, event.getDate(), event.getColor());
        calendarView.addDecorator(eventDecorator);
    

【讨论】:

这一行有一些非法的agrument.. EventDecorator eventDecorator = new EventDecorator(event.getDate(), event.getColor()); @大卫 其实@Neo 等一下,有个bug java.lang.NumberFormatException: 在颜色解析中 我在答案中写道 - 你没有在 JSON 中指定颜色的格式。 @Neo 我现在要睡觉了——我的回答足以达到你想要的效果。您将不得不使用您的调试技能和编程技能来完成最后一英里,因为我无法访问您的整个项目,包括您的 JSON 的完整规范。这只是一个合理的预期。这是解析颜色的链接:***.com/questions/5248583/…

以上是关于如何更改 MaterialCalendarView 中日历日期的背景颜色的主要内容,如果未能解决你的问题,请参考以下文章

日历在 MaterialCalendarView 中返回不正确的 MONTH、YEAR 和 DAY_OF_MONTH

Android Spans介绍(转)

如何更改主题更改时浮动操作按钮的颜色?

Ubuntu系统如何更改用户密码

更改模式时如何更改导航阴影颜色?

如何更改分区ID为AF?