自定义签到功能(copy到项目该删的删该改的改)
1、实现思路:GridView显示日历,条项点击事件处理签到逻辑(难点在如何绘制日历,并让日期与星期,月份一致)
2、上代码:
一、xml文件:
二、java代码:
modle类:
package com.whzg.zbjy.modle;
import java.util.List;
/**
*
*/
public class SigninInfoResponseBean {
/**
* Error : null
* Data : {"IsSignIn":true,"DataArr":[10,14],"runningDay":1,"integration":2}
*/
private Object Error;
/**
* IsSignIn : true
* DataArr : [10,14]
* runningDay : 1
* integration : 2
*/
private DataBean Data;
public Object getError() {
return Error;
}
public void setError(Object Error) {
this.Error = Error;
}
public DataBean getData() {
return Data;
}
public void setData(DataBean Data) {
this.Data = Data;
}
public static class DataBean {
private boolean IsSignIn;
private int runningDay;
private int integration;
private List DataArr;
public boolean isIsSignIn() {
return IsSignIn;
}
public void setIsSignIn(boolean IsSignIn) {
this.IsSignIn = IsSignIn;
}
public int getRunningDay() {
return runningDay;
}
public void setRunningDay(int runningDay) {
this.runningDay = runningDay;
}
public int getIntegration() {
return integration;
}
public void setIntegration(int integration) {
this.integration = integration;
}
public List getDataArr() {
return DataArr;
}
public void setDataArr(List DataArr) {
this.DataArr = DataArr;
}
}
}
Application:
package com.whzg.zbjy.ui;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.whzg.zbjy.dbutils.SharedPreferencesUtils;
import java.util.HashMap;
import java.util.Map;
import cn.smssdk.SMSSDK;
/**
*
*/
public class MyApplication extends Application {
private Map map;
public static String CURRENTUSER = "currentuser";
public static String USERNAME="username";
public static String PASSWORD="password";
public static String NAME="name";
public static String SEX="sex";
public static String ADDRESS="address";
public static String SHOOL="shool";
public static String ISLOGIN="islogin";
public static String HEADIMG="headimg";
public static String SIGNINSCORE="signinscore";
@Override
public void onCreate() {
super.onCreate();
SMSSDK.initSDK(this, "18a59f3fd6d52", "b7436f6c091acf826e38abf79e215472");
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(config);
// map = new HashMap();
// //默认的当前账号信息
// map.put("username", "1");
// map.put("password","1");
// map.put("name","未登录");
// map.put("sex","未设置");
// map.put("address","未设置");
// map.put("shool", "未设置");
// map.put("islogin","-1");//0未登录1登录 -1默认状态
// new SharedPreferencesUtils().saveDataToSharedPreferences(this, CURRENTUSER, map);
}
}
SharedPreference:
package com.whzg.zbjy.dbutils;
import android.content.Context;
import android.content.SharedPreferences;
import com.whzg.zbjy.ui.MyApplication;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class SharedPreferencesUtils {
/**
* 获取Sharedpreference数据
* @param context
* @param fileName
* @return
*/
public Map readDataFromSharedPreferences(Context context, String fileName) {
Map map; //Map对象,用于存储读取到的数据
SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
map = sharedPreferences.getAll();
return map;
}
/**
* 保存Sharedpreference数据
* @param context
* @param fileName
* @param map
* @return
*/
public boolean saveDataToSharedPreferences(Context context, String fileName,Map map) {
boolean isSaveDataSuccess = false; //存储数据成功标志位
SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit(); //创建SharedPreferences.Editor对象
if (map == null){
return isSaveDataSuccess;
}
for (String key:map.keySet()){
edit.putString(key, map.get(key));
}
isSaveDataSuccess = edit.commit(); //提交存储数据
return isSaveDataSuccess;
}
}
BaseActivity:
package com.whzg.zbjy.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* 执行findViewById()
*/
public abstract void findView();
/**
* 执行初始化数据
*/
public abstract void initData();
/**
* 执行View控件的初始化
*/
public abstract void initView();
/**
* 对控件设置点击事件
*/
public abstract void initClicked();
}
联网utils:
package com.whzg.zbjy.httputils;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.whzg.zbjy.dbutils.SharedPreferencesUtils;
import com.whzg.zbjy.modle.ChangeInfoResponseBean;
import com.whzg.zbjy.modle.ChangePasswordResponseBean;
import com.whzg.zbjy.modle.GetHomeworkResponseBean;
import com.whzg.zbjy.modle.LoginResponseBean;
import com.whzg.zbjy.modle.RegistResponseBean;
import com.whzg.zbjy.modle.SigninInfoResponseBean;
import com.whzg.zbjy.modle.TraditionBean;
import com.whzg.zbjy.ui.MyApplication;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.UUID;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
*
*/
public class HttpUtils {
/**
* okhttp异步get方法
*/
public void getAsynHttp() {
OkHttpClient mOkHttpClient = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com");
//可以省略,默认是GET请求
requestBuilder.method("GET", null);
Request request = requestBuilder.build();
Call mcall = mOkHttpClient.newCall(request);
mcall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null != response.cacheResponse()) {
String str = response.cacheResponse().toString();
Log.i("wangshu", "cache---" + str);
} else {
response.body().string();
String str = response.networkResponse().toString();
Log.i("wangshu", "network---" + str);
}
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
// }
// });
}
});
}
public void getSignininfo(final String url, final Handler handler) {
new Thread(){
@Override
public void run() {
super.run();
SigninInfoResponseBean signinInfoResponseBean = null;
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okhttp3.Response response = client.newCall(request).execute();
String str = response.body().string();
str = str.substring(1, str.length() - 1);
str = str.replace("\\\"", "\"");
str = str.replace("\\/", "/");
Gson gson = new Gson();
signinInfoResponseBean = gson.fromJson(str, SigninInfoResponseBean.class);
// Toast.makeText(context,signinInfoResponseBean.toString(),Toast.LENGTH_SHORT).show();
Log.i("ssss",signinInfoResponseBean.toString());
Message message = new Message();
message.what =1;
message.obj = signinInfoResponseBean;
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
/**
*今日签到方法
* @param url 签到url
* @param handler 签到处理类
*/
public void todaySignin(final String url, final Handler handler){
new Thread(){
@Override
public void run() {
super.run();
// SigninInfoResponseBean signinInfoResponseBean = null;
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okhttp3.Response response = client.newCall(request).execute();
String str = response.body().string();
str = str.substring(1, str.length() - 1);
str = str.replace("\\\"", "\"");
str = str.replace("\\/", "/");
Gson gson = new Gson();
// signinInfoResponseBean = gson.fromJson(str, SigninInfoResponseBean.class);
// Toast.makeText(context,signinInfoResponseBean.toString(),Toast.LENGTH_SHORT).show();
// Log.i("ssss",signinInfoResponseBean.toString());
Message message = new Message();
message.what =2;
// message.obj = signinInfoResponseBean;
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
color:
#3F51B5
#303F9F
#FF4081
#ffe74c3c
#ffc0392b
#FFDDDDDD
#ffffff
#fffff0
#ffffe0
#ffff00
#fffafa
#fffaf0
#fffacd
#fff8dc
#fff5ee
#fff0f5
#ffefd5
#ffebcd
#ffe4e1
#ffe4c4
#ffe4b5
#ffdead
#ffdab9
#ffd700
#ffc0cb
#ffb6c1
#ffa500
#ffa07a
#ff8c00
#ff7f50
#ff69b4
#ff6347
#ff4500
#ff1493
#ff00ff
#ff00ff
#a50319
#fdf5e6
#fafad2
#faf0e6
#faebd7
#fa8072
#f8f8ff
#f5fffa
#f5f5f5
#f5f5dc
#f5deb3
#f4a460
#f0ffff
#f0fff0
#f0f8ff
#f0e68c
#f08080
#eee8aa
#ee82ee
#e9967a
#e6e6fa
#e0ffff
#deb887
#dda0dd
#dcdcdc
#dc143c
#db7093
#daa520
#da70d6
#d8bfd8
#d3d3d3
#d3d3d3
#d2b48c
#d2691e
#cd853f
#cd5c5c
#c71585
#c0c0c0
#bdb76b
#bc8f8f
#ba55d3
#b8860b
#b22222
#b0e0e6
#b0c4de
#afeeee
#adff2f
#add8e6
#a9a9a9
#a9a9a9
#a52a2a
#a0522d
#9932cc
#98fb98
#9400d3
#9370db
#90ee90
#8fbc8f
#8b4513
#8b008b
#8b0000
#8a2be2
#87cefa
#87ceeb
#808080
#808080
#808000
#800080
#800000
#7fffd4
#7fff00
#7cfc00
#7b68ee
#778899
#778899
#708090
#708090
#6b8e23
#6a5acd
#696969
#696969
#66cdaa
#6495ed
#5f9ea0
#556b2f
#4b0082
#48d1cc
#483d8b
#4682b4
#4169e1
#40e0d0
#3cb371
#32cd32
#2f4f4f
#2f4f4f
#2e8b57
#228b22
#20b2aa
#1e90ff
#191970
#00ffff
#00ffff
#00ff7f
#00ff00
#00fa9a
#00ced1
#00bfff
#008b8b
#008080
#008000
#006400
#0000ff
#0000cd
#00008b
#000080
#000000
最重要的activity:(中间有跳转二级页面注释掉就行,url的拼接使用项目的签到url)
package com.whzg.zbjy.homepage;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.whzg.zbjy.R;
import com.whzg.zbjy.dbutils.SharedPreferencesUtils;
import com.whzg.zbjy.httputils.HttpUtils;
import com.whzg.zbjy.modle.SigninInfoResponseBean;
import com.whzg.zbjy.ui.BaseActivity;
import com.whzg.zbjy.ui.MyApplication;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class SignInActivity extends BaseActivity {
private Toolbar toolbar;
private TextView signin_score, tv_date, signin_login;
private GridView gv_sign_date;
private Button siginin_change;
private SigninInfoResponseBean signinInfoResponseBean = null;
private MyCalenderAdapter myCalenderAdapter = null;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1://获取签到信息
signinInfoResponseBean = (SigninInfoResponseBean) msg.obj;
// if (null != signinInfoResponseBean) {
// Toast.makeText(SignInActivity.this, signinInfoResponseBean.toString(), Toast.LENGTH_SHORT).show();
// }
//在当前用户文件中创建积分项存储积分信息
Map map = new HashMap<>();
map.put(MyApplication.SIGNINSCORE, String.valueOf(signinInfoResponseBean.getData().getIntegration()));
new SharedPreferencesUtils().saveDataToSharedPreferences(SignInActivity.this,MyApplication.CURRENTUSER,map);
myCalenderAdapter.notifyDataSetChanged();//刷新适配器
break;
case 2://今日签到
// Toast.makeText(SignInActivity.this, "22222222", Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
findView();
initData();
initView();
initClicked();
}
@Override
public void findView() {
toolbar = (Toolbar) findViewById(R.id.signin_toolbar);
//我的积分
signin_score = (TextView) findViewById(R.id.signin_score);
//所选日期
tv_date = (TextView) findViewById(R.id.tv_date);
//签到说明
signin_login = (TextView) findViewById(R.id.signin_login);
//日历实体
gv_sign_date = (GridView) findViewById(R.id.gv_sign_date);
//积分兑换
siginin_change = (Button) findViewById(R.id.siginin_change);
}
@Override
public void initData() {
//得到当前登录的手机号
String phone = (String) new SharedPreferencesUtils().readDataFromSharedPreferences(SignInActivity.this, MyApplication.CURRENTUSER).get(MyApplication.USERNAME);
// Toast.makeText(SignInActivity.this,phone,Toast.LENGTH_SHORT).show();
new HttpUtils().getSignininfo(getResources().getString(R.string.get_signininfo) + phone, handler);
}
@Override
public void initView() {
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setTitle("");
toolbar.setSubtitle("");
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SignInActivity.this.finish();
}
});
//签到说明
signin_login.setText("签到说明:\n\n连续签到一天得一分;\n连续签到二天得二分;\n连续签到三天得三分;\n······");
//当前日期
tv_date.setText(Calendar.getInstance().get(Calendar.YEAR) + "-" + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "-" + Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
myCalenderAdapter = new MyCalenderAdapter();
gv_sign_date.setAdapter(myCalenderAdapter);
//积分兑换
siginin_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SignInActivity.this,SignIn2Activity.class));
}
});
signin_score.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SignInActivity.this,SignIn2Activity.class));
}
});
}
@Override
public void initClicked() {
gv_sign_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
int i = (int) view.getTag();
if (i != 0) {//设置选中的日期
tv_date.setText(Calendar.getInstance().get(Calendar.YEAR) + "-" + (Calendar.getInstance().get(Calendar.MONTH) + 1) + "-" + i);
}
if (i == Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) {//点击当前日期则执行签到操作
String phone = (String) new SharedPreferencesUtils().readDataFromSharedPreferences(SignInActivity.this, MyApplication.CURRENTUSER).get(MyApplication.USERNAME);
int runningday = 0;//连续签到数
int plusIntegral = 1;//签到积分
int endday = signinInfoResponseBean.getData().getDataArr().get(signinInfoResponseBean.getData().getDataArr().size() - 1);
if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == endday + 1) {//判断是否连续签到
runningday = signinInfoResponseBean.getData().getRunningDay() + 1;
plusIntegral = runningday;
}
if (runningday>30){//当连续签到数大于30时重新计数
runningday=0;
plusIntegral=1;
}
new HttpUtils().todaySignin(getResources().getString(R.string.today_signin) + phone + "," + runningday + "," + plusIntegral, handler);
TextView textView = (TextView) view.findViewById(R.id.siginin_gv_item_tv);
textView.setBackgroundColor(getResources().getColor(R.color.chartreuse));
}
}
});
}
class MyCalenderAdapter extends BaseAdapter {
private int firstColumn = 0, count = 0;
private Calendar calendar;
private int mYear, mMonth, mDay, mWay, mHour, mMinute;
public MyCalenderAdapter() {
this.calendar = Calendar.getInstance();//日历实例
this.firstColumn = getColumnIndex(1);//月份第一天的列号
int month = calendar.get(Calendar.MONTH) + 1;
this.count = getDayNumOfMonth(month) + firstColumn;
this.mYear = calendar.get(Calendar.YEAR); // 获取当前年份
this.mMonth = calendar.get(Calendar.MONTH) + 1;// 获取当前月份
this.mDay = calendar.get(Calendar.DAY_OF_MONTH);// 获取当日期
this.mWay = calendar.get(Calendar.DAY_OF_WEEK);// 获取当前日期的星期
this.mHour = calendar.get(Calendar.HOUR_OF_DAY);//时
this.mMinute = calendar.get(Calendar.MINUTE);//分
}
@Override
public int getCount() {
return count;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(SignInActivity.this).inflate(R.layout.signin_gv_item, null);
TextView textView = (TextView) view.findViewById(R.id.siginin_gv_item_tv);
if (position < firstColumn) {
textView.setText("");
view.setTag(0);
} else {
textView.setText(String.valueOf(position - firstColumn + 1));
view.setTag(position - firstColumn + 1);//使用tag存储当前view是哪一天
}
if ((int) view.getTag() < mDay) {
textView.setTextColor(SignInActivity.this.getResources().getColor(R.color.lightgray));
}
if ((int) view.getTag() == mDay) {
textView.setBackgroundColor(SignInActivity.this.getResources().getColor(R.color.gray));
textView.setTextColor(SignInActivity.this.getResources().getColor(R.color.white));
}
if (null != signinInfoResponseBean) {
for (int i = 0; i < signinInfoResponseBean.getData().getDataArr().size(); i++) {
int signdate = signinInfoResponseBean.getData().getDataArr().get(i);
int date = (int) view.getTag();
if (date == signdate) {
textView.setBackgroundColor(SignInActivity.this.getResources().getColor(R.color.chartreuse));
textView.setTextColor(SignInActivity.this.getResources().getColor(R.color.white));
}
}
}
return view;
}
/**
* 获取列序号
*
* @param dayOfMonth 日期
* @return 列序号
*/
private int getColumnIndex(int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY) {
dayOfWeek = 6;
} else {
dayOfWeek = dayOfWeek - 2;
}
return dayOfWeek;
}
/**
* 获取行序号
*
* @param dayOfMonth 日期
* @return 行序号
*/
private int getRowIndex(int dayOfMonth) {
float weight = (dayOfMonth - getColumnIndex(dayOfMonth)) / (7 * 1f);
double rowIndexDouble = Math.abs(Math.ceil(weight));
return (int) rowIndexDouble;
}
/**
* @param month 月份
* @return 某月天数
*/
private int getDayNumOfMonth(int month) {
switch (month) {
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (Calendar.getInstance().get(Calendar.YEAR) % 4 == 0) {
return 29;
}
return 28;
default:
return 31;
}
}
}
}