先上图:左右滑动显示上个月和下个月,点击左上角日期区域出现时间选择器,设置显示时间
使用ViewPager左右滑动,在每页动态添加GridView,GridView显示当前月的日期,具体看代码中的注释。
MainActivity:
package com.example.calendardemo;
import java.util.Calendar;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
@SuppressLint("InlinedApi")
public class MainActivity extends Activity implements OnClickListener {
// 基本变量
private GridView title_gView;
private Calendar calStartDate = Calendar.getInstance();// 当前显示的日历
private Calendar calSelectDate = Calendar.getInstance();// 当前选择的日历
private LinearLayout mCalendarLayout;
private ImageView mPreImg;
private ImageView mNextImg;
private TextView mSelectedMonthTx;
private TextView mYearTx;
private TextView mMonthTx;
private TextView mDayTx;
private TextView mWeekTx;
// -------------------------------------------------------------------------
public MyViewPager viewPager = null;
public MyPagerAdapter pagerAdapter = null;
// private GridView gView;
// private CalendarGridViewAdapter gAdapter;
private int currPager = 500;
private CalendarGridViewAdapter adapter = null;
private GridView currentView = null;
// -------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
* 初始化View
*/
private void initView() {
viewPager = (MyViewPager) findViewById(R.id.stc_calendar_viewpager);
mYearTx = (TextView) findViewById(R.id.stc_year_tx);
mMonthTx = (TextView) findViewById(R.id.stc_month_tx);
mWeekTx = (TextView) findViewById(R.id.stc_week_tx);
mDayTx = (TextView) findViewById(R.id.stc_day_tx);
mYearTx.getPaint().setFakeBoldText(true);
mMonthTx.getPaint().setFakeBoldText(true);
mWeekTx.getPaint().setFakeBoldText(true);
mDayTx.getPaint().setFakeBoldText(true);
mDayTx.setOnClickListener(this);
mWeekTx.setOnClickListener(this);
mMonthTx.setOnClickListener(this);
mCalendarLayout = (LinearLayout) findViewById(R.id.stc_calendar_layout);
mPreImg = (ImageView) findViewById(R.id.stc_pre_month_img);
mPreImg.setOnClickListener(this);
mNextImg = (ImageView) findViewById(R.id.stc_next_month_img);
mNextImg.setOnClickListener(this);
mSelectedMonthTx = (TextView) findViewById(R.id.stc_select_month_tx);
setTitleGirdView();
LinearLayout.LayoutParams params_cal_title = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
mCalendarLayout.addView(title_gView, params_cal_title);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.stc_pre_month_img:
showPreMonth();
break;
case R.id.stc_next_month_img:
showNextMonth();
break;
case R.id.stc_day_tx:
case R.id.stc_month_tx:
case R.id.stc_week_tx:// 点击时间出现时间选择器
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, setDateCallBack, year, month, day);
dialog.show();
// dialogTitleLineColor(dialog, 0xffff6d4b);
break;
default:
break;
}
}
/**
* 时间选择器titleDivider的颜色
*/
public final void dialogTitleLineColor(Dialog dialog, int color) {
Context context = dialog.getContext();
int divierId = context.getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = dialog.findViewById(divierId);
divider.setBackgroundColor(color);
}
/**
* 回调函数,int year, int monthOfYear, int dayOfMonth三个参数为日期对话框设置的日期
*/
private OnDateSetListener setDateCallBack = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
calStartDate.set(year, monthOfYear, dayOfMonth);
initData();
}
};
/**
* 初始化数据
*/
private void initData() {
setDateUI(calStartDate);
initCalendar();
}
/**
* 更新顶部的日期控件数据
*/
private void setDateUI(Calendar cal) {
mSelectedMonthTx.setText(JTimeUtils.getShowTimeTx(this, cal.get(Calendar.MONTH) + 1));
mYearTx.setText(String.valueOf(cal.get(Calendar.YEAR)));
mMonthTx.setText(JTimeUtils.getMonthAbbreviation(cal.get(Calendar.MONTH) + 1));
mDayTx.setText(cal.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + cal.get(Calendar.DAY_OF_MONTH) : "" + cal.get(Calendar.DAY_OF_MONTH));
mWeekTx.setText(JTimeUtils.getWeekAbbreviation(cal.get(Calendar.DAY_OF_WEEK) - 1));
}
@Override
public void onResume() {
super.onResume();
calStartDate = Calendar.getInstance();
initData();
}
@Override
public void onPause() {
super.onPause();
// calSelectDate.setTime(calStartDate.getTime());
}
private GridView setGirdView() {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
GridView gridView = new GridView(this);
gridView.setLayoutParams(params);
gridView.setNumColumns(7);// 设置每行列数
gridView.setGravity(Gravity.CENTER_VERTICAL);// 位置居中
gridView.setVerticalSpacing(1);// 垂直间隔
gridView.setHorizontalSpacing(1);// 水平间隔
gridView.setBackgroundColor(Color.TRANSPARENT);
gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
return gridView;
}
private void setTitleGirdView() {
title_gView = setGirdView();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
title_gView.setLayoutParams(params);
title_gView.setVerticalSpacing(1);// 垂直间隔
title_gView.setHorizontalSpacing(1);// 水平间隔
TitleGridAdapter titleAdapter = new TitleGridAdapter(this);
title_gView.setAdapter(titleAdapter);// 设置菜单Adapter
}
public class TitleGridAdapter extends BaseAdapter {
int[] titles = new int[] { R.string.sunday, R.string.monday, R.string.tuesday,
R.string.wednesday, R.string.thursday, R.string.friday, R.string.saturday };
private Activity activity;
// construct
public TitleGridAdapter(Activity a) {
activity = a;
}
@Override
public int getCount() {
return titles.length;
}
@Override
public Object getItem(int position) {
return titles[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout iv = new LinearLayout(activity);
TextView txtDay = new TextView(activity);
txtDay.setFocusable(false);
txtDay.setBackgroundColor(Color.TRANSPARENT);
iv.setOrientation(LinearLayout.HORIZONTAL);
txtDay.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
txtDay.setTextColor(0xff999999);
txtDay.setText((Integer) getItem(position));
iv.addView(txtDay, lp);
return iv;
}
}
/**
* 初始化滑动控件ViewPager
*/
private void initCalendar() {
pagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(500);// 设置当前页位置为500
viewPager.setPageMargin(0);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int arg0) {
if (arg0 == 1) {
}
if (arg0 == 0) {
currentView = (GridView) viewPager.findViewById(currPager);
if (currentView != null) {
adapter = (CalendarGridViewAdapter) currentView.getAdapter();
}
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageSelected(int position) {
// 滑动到某页后更新数据、UI
Calendar tempSelected = Calendar.getInstance(); // 临时
tempSelected.setTime(calStartDate.getTime());
int count = position - 500;
tempSelected.add(Calendar.MONTH, count);
int month = tempSelected.get(Calendar.MONTH) + 1;
mSelectedMonthTx.setText(JTimeUtils.getShowTimeTx(MainActivity.this, month));
setDateUI(tempSelected);
currPager = position;
calSelectDate.set(tempSelected.get(Calendar.YEAR), tempSelected.get(Calendar.MONTH), tempSelected.get(Calendar.DAY_OF_MONTH));
}
});
}
/**
* ViewPager的适配器,从第500页开始,最多支持0-1000页
*/
private class MyPagerAdapter extends PagerAdapter {
@Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
}
@Override
public int getCount() {
return 1000;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
GridView gv = initCalendarView(position);
gv.setId(position);
container.addView(gv);
return gv;
}
}
/**
* 动态生成GridView
*/
private GridView initCalendarView(int position) {
int count = position - 500;
Calendar tempSelected = Calendar.getInstance(); // 临时
/*if (position == 500) {
int month = tempSelected.get(Calendar.MONTH) + 1;
mSelectedMonthTx.setText(TimeUtils.getShowTimeTx(this, month));
}*/
tempSelected.setTime(calStartDate.getTime());
GridView gView = new CalendarGridView(this);
tempSelected.add(Calendar.MONTH, count);
final CalendarGridViewAdapter gAdapter = new CalendarGridViewAdapter(this, tempSelected, position);
gView.setAdapter(gAdapter);// 设置菜单Adapter
gView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
// item点击事件
// do somethings
}
});
return gView;
}
/**
* 滑动到上一页
*/
private void showPreMonth() {
viewPager.setCurrentItem(--currPager, true);
}
/**
* 滑动到下一页
*/
private void showNextMonth() {
viewPager.setCurrentItem(++currPager, true);
}
}
package com.example.calendardemo;
import android.app.Activity;
import android.content.res.Resources;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class CalendarGridViewAdapter extends BaseAdapter {
private Calendar calStartDate = Calendar.getInstance();// 当前显示的日历
private Calendar calDate = Calendar.getInstance();
private LayoutInflater mInflater;
private int mDisplayWidth = 0;
private int mGridWidth = 0;
private List mListData = new ArrayList();
private Activity activity;
Resources resources;
private int iMonthViewCurrentMonth = 0; // 当前视图月
public CalendarGridViewAdapter(Activity a, Calendar cal, int pos) {
activity = a;
resources = activity.getResources();
calStartDate = cal;
calDate.setTime(cal.getTime());
getDates();
mInflater = LayoutInflater.from(a);
getGridWidth();
}
/**
* 根据改变的日期更新日历,填充日历控件用
*/
private void UpdateStartDateForMonth() {
calStartDate.set(Calendar.DATE, 1); // 设置成当月第一天
iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);// 得到当前日历显示的月
// 星期一是2 星期天是1 填充剩余天数
int iDay = 0;
int iFirstDayOfWeek = Calendar.SUNDAY;
int iStartDay = iFirstDayOfWeek;
if (iStartDay == Calendar.MONDAY) {
iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
if (iDay < 0)
iDay = 6;
}
if (iStartDay == Calendar.SUNDAY) {
iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
if (iDay < 0)
iDay = 6;
}
calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);
}
private void getDates() {
UpdateStartDateForMonth();
for (int i = 1; i <= 42; i++) {
mListData.add(calStartDate.getTime());
calStartDate.add(Calendar.DAY_OF_MONTH, 1);
}
}
@SuppressWarnings("deprecation")
private void getGridWidth() {
Display display = activity.getWindowManager().getDefaultDisplay();
mDisplayWidth = display.getWidth();
float scale = activity.getResources().getDisplayMetrics().density;
mGridWidth = (mDisplayWidth - (int) (46 * scale)) / 7;// 46dp位距离两边的margin
}
@Override
public int getCount() {
return mListData.size();
}
@Override
public Object getItem(int position) {
return mListData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressWarnings("deprecation")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.calendar_grid_view_item, null);
holder = new ViewHolder();
holder.itemPic = (ImageView) convertView
.findViewById(R.id.stc_cal_grid_item_pic);
holder.itemPicMask = (ImageView) convertView
.findViewById(R.id.stc_cal_grid_item_pic_mask);
holder.itemDay = (TextView) convertView
.findViewById(R.id.stc_cal_grid_item_day);
holder.itemLayout = (RelativeLayout) convertView
.findViewById(R.id.stc_cal_grid_item_layout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Date myDate = (Date) getItem(position);
Calendar calCalendar = Calendar.getInstance();
calCalendar.setTime(myDate);
final int iMonth = calCalendar.get(Calendar.MONTH);
// final int iDay = calCalendar.get(Calendar.DAY_OF_WEEK);
int day = myDate.getDate(); // 日期
holder.itemDay.setText(String.valueOf(day));
holder.itemPic.setVisibility(View.GONE);
holder.itemPicMask.setVisibility(View.GONE);
if (equalsDate(calDate.getTime(), myDate)) {
// 当前日期
holder.itemLayout
.setBackgroundResource(R.drawable.stc_calendar_item_select_bg);
holder.itemDay.setTextColor(0xFFFFFFFF);
} else {
holder.itemLayout
.setBackgroundResource(R.drawable.stc_calendar_item_normal_bg);
holder.itemDay.setTextColor(0xFF8F8F8F);
}
// 判断是否是当前月,不是当前月不显示
if (iMonth == iMonthViewCurrentMonth) {
holder.itemLayout.setVisibility(View.VISIBLE);
} else {
holder.itemLayout.setVisibility(View.GONE);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
mGridWidth, mGridWidth);
holder.itemLayout.setLayoutParams(params);
/**
* convertView设置了setLayoutParams后,如果在此函数中设置某个控件的click事件,会出现第一格点击没有响应的情况,
* 解决方法是设置GridView的onItemClick事件
*/
convertView.setLayoutParams(new GridView.LayoutParams(
LayoutParams.WRAP_CONTENT, mGridWidth));
return convertView;
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
/**
* 比较时间
*
*/
private Boolean equalsDate(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(date1.getTime());
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(date2.getTime());
int day1 = cal1.get(Calendar.DAY_OF_MONTH);
int day2 = cal2.get(Calendar.DAY_OF_MONTH);
if (day2 == day1) {
return true;
}
return false;
}
private class ViewHolder {
public ImageView itemPic;
public ImageView itemPicMask;
public TextView itemDay;
public RelativeLayout itemLayout;
}
}