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

时间:2022-08-14 20:17:07

I'm trying to change the background color of dates using a JSON response I get. But I'm having some difficulty.

我想更改日期的背景色使用JSON响应。但是我有一些困难。

Here is my code:

这是我的代码:

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

MainActivty.java

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 response

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
      },

   ]
}  

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

1 个解决方案

#1


1  

The first step is to create a DayViewDecorator that will take as parameters a Date and a color:

第一步是创建一个DayViewDecorator,它将把日期和颜色作为参数:

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);
    }
}

(N.B. I used the code in this answer to apply the tint. Also, since you didn't specify, I have assumed that the drawable is some kind of image that needs tinting in this way.)

注意:我用这个答案中的代码来应用色彩。另外,由于您没有指定,我假设drawable是某种需要用这种方式着色的图像。

The next step is to create an Event class for storing the events you parse from the API call:

下一步是创建一个事件类来存储您从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;
    }
}

Now we need to add logic to your onResponse() method to parse the JSON and add decorators for each event. It is hard to know what exactly to write because you haven't given a sample of the JSON. Your previous questions show that you already know how to parse a Date so I think this will be enough. Since you haven't specified, I'll leave it out for now. Also, I'm just appending to your code - I won't try and refactor it much.

现在我们需要向onResponse()方法添加逻辑来解析JSON并为每个事件添加修饰符。很难知道具体要写什么,因为您还没有给出JSON的示例。您之前的问题表明您已经知道如何解析日期,因此我认为这就足够了。既然你没有说明,我现在就不讲了。另外,我只是添加到您的代码中—我不会尝试重构它。

@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);
    }
}

#1


1  

The first step is to create a DayViewDecorator that will take as parameters a Date and a color:

第一步是创建一个DayViewDecorator,它将把日期和颜色作为参数:

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);
    }
}

(N.B. I used the code in this answer to apply the tint. Also, since you didn't specify, I have assumed that the drawable is some kind of image that needs tinting in this way.)

注意:我用这个答案中的代码来应用色彩。另外,由于您没有指定,我假设drawable是某种需要用这种方式着色的图像。

The next step is to create an Event class for storing the events you parse from the API call:

下一步是创建一个事件类来存储您从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;
    }
}

Now we need to add logic to your onResponse() method to parse the JSON and add decorators for each event. It is hard to know what exactly to write because you haven't given a sample of the JSON. Your previous questions show that you already know how to parse a Date so I think this will be enough. Since you haven't specified, I'll leave it out for now. Also, I'm just appending to your code - I won't try and refactor it much.

现在我们需要向onResponse()方法添加逻辑来解析JSON并为每个事件添加修饰符。很难知道具体要写什么,因为您还没有给出JSON的示例。您之前的问题表明您已经知道如何解析日期,因此我认为这就足够了。既然你没有说明,我现在就不讲了。另外,我只是添加到您的代码中—我不会尝试重构它。

@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);
    }
}