Native Mobile App Development With Java

Android CalanderView

15-Sep-2024

How to implement CalendarView in Android applications using Java to show a calendar widget

Example of using CalendarView in an Android application



Here is the tutorial for Kotlin




There Are Some Common Attributes for CalanderView :

id
This ID serves as the control's unique identity.
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size
layout_widthmatch_parent -> Text area contains fullscreen
wrap_content-> Text area contains only text size





Step 1:
File open res/layout/activity_main.xml file −


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">

<CalendarView
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>



Step 2:

File open com.microappvalley.newtestproject/MainActivity.java file −

Java:

package com.microappvalley.newtestproject;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


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


CalendarView calendarView = findViewById(R.id.calendarView);

// Set a listener to handle date selection
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
// Display the selected date
String selectedDate = "Selected Date: " + (month + 1) + "/" + dayOfMonth + "/" + year;
Toast.makeText(MainActivity.this, selectedDate, Toast.LENGTH_SHORT).show();
}
});
}
}




Open Device Manager, run the emulator, and  then run the application. Next, check the working output and check the output  you declared in your code.


Output:


Comments