2016-12-20 15 views
2

JSON 응답을 사용하여 날짜의 배경색을 변경하려고합니다. 그러나 나는 어려움을 겪고있다.MaterialCalendarView에서 달력 날짜의 배경색을 변경하는 방법

<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

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

    ] 
} 

enter image description here

0,123,516 : 여기

내 코드입니다

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. :

+0

레이아웃에 표시되는 모양과 보려는 모양의 이미지를 추가 할 수 있습니까? – Flummox

+0

현재이 모양과 나는 이벤트 날짜의 뒤를 바꾸고 싶다 @Flummox –

답변

1

첫 번째 단계는 Date와 색상을 파라미터로서 취할 것 DayViewDecorator을 만드는 것이다 나는 this answer의 코드를 사용하여 색조를 적용했습니다. 또한 지정하지 않았으므로이 드로어 블이 이런 식으로 색조가 필요한 이미지라고 가정했습니다.)

다음 단계는 API에서 파싱 한 이벤트를 저장하기위한 Event 클래스를 만드는 것입니다. 전화 :

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

지금 우리는 JSON을 구문 분석하고 각 이벤트에 대해 장식을 추가 할 onResponse() 방법에 로직을 추가해야합니다. 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); 
    } 
} 
+0

이 줄에 불법적 인 악기가있다 .. EventDecorator eventDecorator = new EventDecorator (event.getDate(), event.getColor()); @David –

+0

실제로 @Neo 그냥 잠깐, 거기에 버그가있어 –

+0

java.lang.NumberFormatException : 색상 파싱 –