PG備忘録

プログラミングいろいろ

Calendarアプリ

f:id:olee46:20170601103012j:plain
機能:
・カレンダーを表示
・左右の矢印をクリックすると、月を変えられる
・「月別」ボタンは特に何もしない


注意点:
・Calendar.MONTH は 1月=0, 2月=1, ... ,12月=11 の値を取るので、月をテキストで表示するときは +1 をする


activity_main.xml
Gridlayoutの中にボタンを 6*7 = 42コ 配置する
f:id:olee46:20170601103013j:plain


MainActivity.java
package com.example.orisa.mycalendar1;

import android.icu.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//部品の変数
Button[] btnTable = new Button[43];
Button btnLeft;
Button btnRight;
TextView ymTv;

//カレンダー変数
Calendar cal = Calendar.getInstance();

//現在の日付・曜日を取得
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int dow = cal.get(Calendar.DAY_OF_WEEK);//日=1, 月=2, 火=3, 水=4, 木=5, 金=6, 土=7
int today = day;

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

//部品の取得
btnLeft = (Button)findViewById(R.id.btnLeft);
btnRight = (Button)findViewById(R.id.btnRight);
ymTv = (TextView)findViewById(R.id.ymTv);

//矢印のボタンにリスナーをつける
btnLeft.setOnClickListener(this);
btnRight.setOnClickListener(this);

//配列にボタンを格納
for(int i = 1; i < btnTable.length; i++){
String btnId = "btn"+i;
int resId = getResources().getIdentifier(btnId, "id", getPackageName());
btnTable[i] = (Button)findViewById(resId);
btnTable[i].setOnClickListener(this);
}

//年と月を設定
ymTv.setText(year + " / " + (month+1));

//ボタンに文字を割り当てる
cal.set(year, month, 1);//今月初日に設定

day = cal.get(Calendar.DAY_OF_MONTH);//今月初日の日
dow = cal.get(Calendar.DAY_OF_WEEK);//今月初日の曜日
Toast.makeText(this, String.valueOf(month), Toast.LENGTH_LONG).show();

cal.add(Calendar.MONTH, 1);//来月に設定
cal.add(Calendar.DATE, -1);//来月初日-1 = 今月の末日に設定
int lastdate = cal.get(Calendar.DATE);//今月の末日

for(int i = dow; i<=dow+lastdate-1;i++){
btnTable[i].setText(String.valueOf(day));
//今日の日付の色を変える
if(i == dow+today-1){
btnTable[i].setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}
day++;
}

}

@Override
public void onClick(View v) {
if(v == btnLeft){//月を一つ前にずらす
if(month == 0){
month = 11;
year = year - 1;
}else{
month = month - 1;
}
}
else if (v == btnRight){
if(month == 11){
month = 1;
year = year + 1;
}else{
month = month + 1;
}
}

//年と月を設定
ymTv.setText(year + " / " + (month+1));
//日付を設定
cal.set(year, month, 1);

day = cal.get(Calendar.DAY_OF_MONTH);
dow = cal.get(Calendar.DAY_OF_WEEK);

cal.add(Calendar.MONTH,1);
cal.add(Calendar.DATE, - 1);
int lastdate = cal.get(Calendar.DATE);

//日付のテキストをクリアする
for(int i = 1; i < btnTable.length; i++){
btnTable[i].setText(null);
}
//日付のテキストを設定
for(int i = dow; i <= dow+lastdate - 1; i++){
btnTable[i].setText(String.valueOf(day++));
}
}
}


参考サイト:
Androidアプリ作成日記 家計簿アプリその10、カレンダー機能