Android Calendars

Miranda Cheung
2 min readJan 17, 2018

--

This tutorial is for a monthly calendar that opens a new activity when a date is clicked.

To set up the calendar, first add a CalendarView in xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<CalendarView
android:id="@+id/calendarView"
android:layout_width="385dp"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.47"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.794" />
</android.support.constraint.ConstraintLayout>$

Then, wire the computational aspects of the calendar.

public class MainActivity extends AppCompatActivity {
private CalendarView calendar;
private static final String TAG = "Calendar";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendar = findViewById(R.id.calendarView);

calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int day) {
String date = (month+1) "/" + day + "/" + year;
Log.d(TAG, "onSelectedDayChange : mm/dd/yyyy: " + date);
}
});

}
}

Your calendar should be able to do this:

Calendar can switch back and forth between months. Current date highlighted.

For switch screens, create a second layout with a TextView and a Button

Now create the corresponding activity and wire widgets.

public class CalendarActivity extends AppCompatActivity {
private TextView theDate;

private Button back;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
theDate = findViewById(R.id.textView_date);
back = findViewById(R.id.button_back);
Intent incomingI = getIntent();
String date = incomingI.getStringExtra("date");


theDate.setText(date);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(CalendarActivity.this, MainActivity.class);
startActivity(i);
}
});
}

}

To allow for date information from MainActivity to be sent to CalendarActivity, add the following within setOnDateChangeListener in MainActivity

Intent i = new Intent(MainActivity.this, CalendarActivity.class);
i.putExtra("date", date);
startActivity(i);

Done!

--

--