Android学习教程之日历库使用(15)

本教程为大家分享了Android日历库的使用方法,供大家参考,具体内容如下

MainActivity.java代码:

package siso.weekv;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

  findViewById(R.id.buttonBasic).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this, BasicActivity.class);
    startActivity(intent);
   }
  });

  findViewById(R.id.buttonAsynchronous).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this, AsynchronousActivity.class);
    startActivity(intent);
   }
  });
 }

}

AsynchronousActivity.java代码:

package siso.weekv;

import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import siso.weekv.apiclient.Event;
import siso.weekv.apiclient.MyJsonService;
import siso.wvlib.WeekViewEvent;

/**
 * An example of how events can be fetched from network and be displayed on the week view.
 * Created by Raquib-ul-Alam Kanak on 1/3/2014.
 * Website: http://alamkanak.github.io
 */
public class AsynchronousActivity extends BaseActivity implements Callback<List<Event>> {

 private List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
 boolean calledNetwork = false;

 @Override
 public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {

  // Download events from network if it hasn't been done already. To understand how events are
  // downloaded using retrofit, visit http://square.github.io/retrofit
  if (!calledNetwork) {
   RestAdapter retrofit = new RestAdapter.Builder()
     .setEndpoint("https://api.myjson.com/bins")
     .build();
   MyJsonService service = retrofit.create(MyJsonService.class);
   service.listEvents(this);
   calledNetwork = true;
  }

  // Return only the events that matches newYear and newMonth.
  List<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
  for (WeekViewEvent event : events) {
   if (eventMatches(event, newYear, newMonth)) {
    matchedEvents.add(event);
   }
  }
  return matchedEvents;
 }

 /**
  * Checks if an event falls into a specific year and month.
  * @param event The event to check for.
  * @param year The year.
  * @param month The month.
  * @return True if the event matches the year and month.
  */
 private boolean eventMatches(WeekViewEvent event, int year, int month) {
  return (event.getStartTime().get(Calendar.YEAR) == year && event.getStartTime().get(Calendar.MONTH) == month - 1) || (event.getEndTime().get(Calendar.YEAR) == year && event.getEndTime().get(Calendar.MONTH) == month - 1);
 }

 @Override
 public void success(List<Event> events, Response response) {
  this.events.clear();
  for (Event event : events) {
   this.events.add(event.toWeekViewEvent());
  }
  getWeekView().notifyDatasetChanged();
 }

 @Override
 public void failure(RetrofitError error) {
  error.printStackTrace();
  Toast.makeText(this, R.string.async_error, Toast.LENGTH_SHORT).show();
 }
}

BaseActivity.java

package siso.weekv;

import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import siso.wvlib.DateTimeInterpreter;
import siso.wvlib.MonthLoader;
import siso.wvlib.WeekView;
import siso.wvlib.WeekViewEvent;

public abstract class BaseActivity extends AppCompatActivity implements WeekView.EventClickListener, MonthLoader.MonthChangeListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener {
 private static final int TYPE_DAY_VIEW = 1;
 private static final int TYPE_THREE_DAY_VIEW = 2;
 private static final int TYPE_WEEK_VIEW = 3;
 private int mWeekViewType = TYPE_THREE_DAY_VIEW;
 private WeekView mWeekView;

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

  // Get a reference for the week view in the layout.
  mWeekView = (WeekView) findViewById(R.id.weekView);

  // Show a toast message about the touched event.
  mWeekView.setOnEventClickListener(this);

  mWeekView.setMonthChangeListener(this);

  // Set long press listener for events.
  mWeekView.setEventLongPressListener(this);

  mWeekView.setEmptyViewLongPressListener(this);

  setupDateTimeInterpreter(false);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();
  setupDateTimeInterpreter(id == R.id.action_week_view);
  switch (id){
   case R.id.action_today:
    mWeekView.goToToday();
    return true;
   case R.id.action_day_view:
    if (mWeekViewType != TYPE_DAY_VIEW) {
     item.setChecked(!item.isChecked());
     mWeekViewType = TYPE_DAY_VIEW;
     mWeekView.setNumberOfVisibleDays(1);

     // Lets change some dimensions to best fit the view.
     mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
     mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
     mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
    }
    return true;
   case R.id.action_three_day_view:
    if (mWeekViewType != TYPE_THREE_DAY_VIEW) {
     item.setChecked(!item.isChecked());
     mWeekViewType = TYPE_THREE_DAY_VIEW;
     mWeekView.setNumberOfVisibleDays(3);

     // Lets change some dimensions to best fit the view.
     mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
     mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
     mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
    }
    return true;
   case R.id.action_week_view:
    if (mWeekViewType != TYPE_WEEK_VIEW) {
     item.setChecked(!item.isChecked());
     mWeekViewType = TYPE_WEEK_VIEW;
     mWeekView.setNumberOfVisibleDays(7);

     mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
     mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
     mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
    }
    return true;
  }

  return super.onOptionsItemSelected(item);
 }

 private void setupDateTimeInterpreter(final boolean shortDate) {
  mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
   @Override
   public String interpretDate(Calendar date) {
    SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.getDefault());
    String weekday = weekdayNameFormat.format(date.getTime());
    SimpleDateFormat format = new SimpleDateFormat(" M/d", Locale.getDefault());

    if (shortDate)
     weekday = String.valueOf(weekday.charAt(0));
    return weekday.toUpperCase() + format.format(date.getTime());
   }

   @Override
   public String interpretTime(int hour) {
    return hour > 11 ? (hour - 12) + " PM" : (hour == 0 ? "12 AM" : hour + " AM");
   }
  });
 }

 protected String getEventTitle(Calendar time) {
  return String.format("事件 %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH)+1, time.get(Calendar.DAY_OF_MONTH));
 }

 @Override
 public void onEventClick(WeekViewEvent event, RectF eventRect) {
  Toast.makeText(this, "点击 " + event.getName(), Toast.LENGTH_SHORT).show();
 }

 @Override
 public void onEventLongPress(WeekViewEvent event, RectF eventRect) {
  Toast.makeText(this, "长按事件: " + event.getName(), Toast.LENGTH_SHORT).show();
 }

 @Override
 public void onEmptyViewLongPress(Calendar time) {
  Toast.makeText(this, "空视图长按: " + getEventTitle(time), Toast.LENGTH_SHORT).show();
 }

 public WeekView getWeekView() {
  return mWeekView;
 }
}

BasicActivity.java

package siso.weekv;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import siso.wvlib.WeekViewEvent;

public class BasicActivity extends BaseActivity {

 @Override
 public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
  // Populate the week view with some events.
  List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();

  Calendar startTime = Calendar.getInstance();
  startTime.set(Calendar.HOUR_OF_DAY, 3);
  startTime.set(Calendar.MINUTE, 0);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  Calendar endTime = (Calendar) startTime.clone();
  endTime.add(Calendar.HOUR, 1);
  endTime.set(Calendar.MONTH, newMonth-1);
  WeekViewEvent event = new WeekViewEvent(1, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_01));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.HOUR_OF_DAY, 3);
  startTime.set(Calendar.MINUTE, 30);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  endTime = (Calendar) startTime.clone();
  endTime.set(Calendar.HOUR_OF_DAY, 4);
  endTime.set(Calendar.MINUTE, 30);
  endTime.set(Calendar.MONTH, newMonth-1);
  event = new WeekViewEvent(10, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_02));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.HOUR_OF_DAY, 4);
  startTime.set(Calendar.MINUTE, 20);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  endTime = (Calendar) startTime.clone();
  endTime.set(Calendar.HOUR_OF_DAY, 5);
  endTime.set(Calendar.MINUTE, 0);
  event = new WeekViewEvent(10, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_03));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.HOUR_OF_DAY, 5);
  startTime.set(Calendar.MINUTE, 30);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  endTime = (Calendar) startTime.clone();
  endTime.add(Calendar.HOUR_OF_DAY, 2);
  endTime.set(Calendar.MONTH, newMonth-1);
  event = new WeekViewEvent(2, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_02));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.HOUR_OF_DAY, 5);
  startTime.set(Calendar.MINUTE, 0);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  startTime.add(Calendar.DATE, 1);
  endTime = (Calendar) startTime.clone();
  endTime.add(Calendar.HOUR_OF_DAY, 3);
  endTime.set(Calendar.MONTH, newMonth - 1);
  event = new WeekViewEvent(3, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_03));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.DAY_OF_MONTH, 15);
  startTime.set(Calendar.HOUR_OF_DAY, 3);
  startTime.set(Calendar.MINUTE, 0);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  endTime = (Calendar) startTime.clone();
  endTime.add(Calendar.HOUR_OF_DAY, 3);
  event = new WeekViewEvent(4, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_04));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.DAY_OF_MONTH, 1);
  startTime.set(Calendar.HOUR_OF_DAY, 3);
  startTime.set(Calendar.MINUTE, 0);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  endTime = (Calendar) startTime.clone();
  endTime.add(Calendar.HOUR_OF_DAY, 3);
  event = new WeekViewEvent(5, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_01));
  events.add(event);

  startTime = Calendar.getInstance();
  startTime.set(Calendar.DAY_OF_MONTH, startTime.getActualMaximum(Calendar.DAY_OF_MONTH));
  startTime.set(Calendar.HOUR_OF_DAY, 15);
  startTime.set(Calendar.MINUTE, 0);
  startTime.set(Calendar.MONTH, newMonth-1);
  startTime.set(Calendar.YEAR, newYear);
  endTime = (Calendar) startTime.clone();
  endTime.add(Calendar.HOUR_OF_DAY, 3);
  event = new WeekViewEvent(5, getEventTitle(startTime), startTime, endTime);
  event.setColor(getResources().getColor(R.color.event_color_02));
  events.add(event);

  return events;
 }

}

apiclient文件夹下Event.java和MyJsonService.java

package siso.weekv.apiclient;

import android.annotation.SuppressLint;
import android.graphics.Color;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import siso.wvlib.WeekViewEvent;

public class Event {

 @Expose @SerializedName("name")
 private String mName;
 @Expose @SerializedName("dayOfMonth")
 private int mDayOfMonth;
 @Expose @SerializedName("startTime")
 private String mStartTime;
 @Expose @SerializedName("endTime")
 private String mEndTime;
 @Expose @SerializedName("color")
 private String mColor;

 public String getName() {
  return mName;
 }

 public void setName(String name) {
  this.mName = name;
 }

 public int getDayOfMonth() {
  return mDayOfMonth;
 }

 public void setDayOfMonth(int dayOfMonth) {
  this.mDayOfMonth = dayOfMonth;
 }

 public String getStartTime() {
  return mStartTime;
 }

 public void setStartTime(String startTime) {
  this.mStartTime = startTime;
 }

 public String getEndTime() {
  return mEndTime;
 }

 public void setEndTime(String endTime) {
  this.mEndTime = endTime;
 }

 public String getColor() {
  return mColor;
 }

 public void setColor(String color) {
  this.mColor = color;
 }

 @SuppressLint("SimpleDateFormat")
 public WeekViewEvent toWeekViewEvent(){

  // Parse time.
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
  Date start = new Date();
  Date end = new Date();
  try {
   start = sdf.parse(getStartTime());
  } catch (ParseException e) {
   e.printStackTrace();
  }
  try {
   end = sdf.parse(getEndTime());
  } catch (ParseException e) {
   e.printStackTrace();
  }

  // Initialize start and end time.
  Calendar now = Calendar.getInstance();
  Calendar startTime = (Calendar) now.clone();
  startTime.setTimeInMillis(start.getTime());
  startTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
  startTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
  startTime.set(Calendar.DAY_OF_MONTH, getDayOfMonth());
  Calendar endTime = (Calendar) startTime.clone();
  endTime.setTimeInMillis(end.getTime());
  endTime.set(Calendar.YEAR, startTime.get(Calendar.YEAR));
  endTime.set(Calendar.MONTH, startTime.get(Calendar.MONTH));
  endTime.set(Calendar.DAY_OF_MONTH, startTime.get(Calendar.DAY_OF_MONTH));

  // Create an week view event.
  WeekViewEvent weekViewEvent = new WeekViewEvent();
  weekViewEvent.setName(getName());
  weekViewEvent.setStartTime(startTime);
  weekViewEvent.setEndTime(endTime);
  weekViewEvent.setColor(Color.parseColor(getColor()));

  return weekViewEvent;
 }
}
package siso.weekv.apiclient;

import java.util.List;

import retrofit.Callback;
import retrofit.http.GET;

/**
 * Created by Raquib-ul-Alam Kanak on 1/3/16.
 * Website: http://alamkanak.github.io
 */
public interface MyJsonService {

 //https://api.myjson.com/bins/3nh0k
 @GET("/3nh0k")
 void listEvents(Callback<List<Event>> eventsCallback);

}

app项目结构:

Andriod类库项目结构:

项目运行结果如图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • android 开发教程之日历项目实践(一)

    前言:决定开始学习 Android 平台下的软件开发,以日历作为实践项目,进行一周后,基本完成. 为了总结及笔记,并给有需要的朋友借鉴,开始整理本教程. 开始之前: 在编写程序之前,需要进行项目设计,因为是练习项目,主要是确定软件 UI 界面,这是已经完成的屏幕截图: 对这个画面,进一步作分解: 这里总共分解为三个 View 文件: 1:activity_main.xml 作为启动的主画面,新建项目时,首先生成. 2:view_calendar_table.xml 定义月历视图,头部固定,其它行

  • Android自定义日历控件实例详解

    为什么要自定义控件 有时,原生控件不能满足我们对于外观和功能的需求,这时候可以自定义控件来定制外观或功能:有时,原生控件可以通过复杂的编码实现想要的功能,这时候可以自定义控件来提高代码的可复用性. 如何自定义控件 下面我通过我在github上开源的Android-CalendarView项目为例,来介绍一下自定义控件的方法.该项目中自定义的控件类名是CalendarView.这个自定义控件覆盖了一些自定义控件时常需要重写的一些方法. 构造函数 为了支持本控件既能使用xml布局文件声明,也可在ja

  • Android实现日历控件示例代码

    做的是一个酒店的项目,可以选择入住和离开的日期.声明为了省事在网上找的资料,自己修改的逻辑,希望对需要的朋友有帮助.喜欢的给个好评.谢谢啦!祝生活愉快! 先上图 第一步,搭建布局xml <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_w

  • android自定义view之实现日历界面实例

    现在网上有很多自定义view实现日历的demo,今天讲一讲如何自己实现这个自定义view. 看一下最终效果图: 在这个自定义view中,我使用了各种奇技淫巧的方法来实现这个日历,真是费尽心思.废话少说,开始进坑. 界面分析 头部是一个textview,显示年份和月份,然后下边一行是星期几,这两行可以固定住,不随月份切换而进出屏幕. 再下边就是我们自定义view 的主角,每个月的天数.目前规定是星期日为每星期第一天.上个月的天数填充满第一行,下个月的前几天填充完最后一行,颜色设置为灰色,本月日期中

  • android 开发教程之日历项目实践(二)

    一.创建 Android Project 在新建对话框中输入 App 属性,SDK版本全部选最新的,不作版本兼容.主题选择 Holo Dark. 下一步,使用默认设置 下一步,使用默认设置 下一步,使用默认配置 下一步,使用默认设置 创建完成后的初始画面 在上面的步骤中,我们选择了创建 MainActivity,ADT 帮我们在 src 目录下生成了 MainActivity.java 文件,在 res/layout/ 目录下生成了 activity_main.xml 文件,并在编辑窗口打开,如

  • android 开发教程之日历项目实践(三)

    二.创建样式 日历显示的表格线,使用 Cell 填充图形的边框来实现,为了统一,我们先定义边框线的颜色及线条精细. 另外还要定义一系统填充样式等. 创建 color: color_calendar_border 表格线color_calendar_title_gregorian 标题栏日期年月文字的颜色color_calendar_title_lunar 标题栏农历color_calendar_title_startcolor_calendar_title_endcolor_calendar_t

  • Android学习教程之日历控件使用(7)

    本文实例为大家分享了Android日历控件的使用方法,供大家参考,具体内容如下 MainActivity.java代码: package siso.timessquare; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; p

  • Android使用GridLayout绘制自定义日历控件

    效果图 思路:就是先设置Gridlayout的行列数,然后往里面放置一定数目的自定义日历按钮控件,最后实现日历逻辑就可以了. 步骤: 第一步:自定义日历控件(初步) 第二步:实现自定义单个日期按钮控件 第三步:将第二步得到的控件动态添加到第一步的布局中,并实现日期逻辑 第四步:编写单个日期点击监听器接口 第一步:自定义日历控件(初步) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmln

  • Android实现自定义日历

    自定义日历控件,支持旧历.节气.日期标注.点击操作 (参考网络上的日历控件改写) 注:将下面的四张资源图片拷贝到所建包的下一个image目录中,如Calendar.java 所在包为 cc.util.android.view,则需要再创建一个包cc.util.android.view.image 然后将图片拷贝进去 /****************从此出开始将代码拷贝到一个文件中*******************/ package cc.util.android.view; import

  • java制作android 日历代码分享

    代码很简单,就不多废话了 复制代码 代码如下: //读取日历事件     public static void getCalendarInfo(Activity activity,String tag){         String[] projection = new String[]{CalendarContract.Events._ID,CalendarContract.Events.TITLE};         ContentResolver cr = activity.getCon

随机推荐