Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android 앱에서 CalendarView 클래스를 활용한 캘린더 위젯 구현 방법

이 예제에서는 Android 앱에서 CalendarView 클래스를 사용해 캘린더 위젯을 구현하고, 사용자가 선택한 날짜를 화면에 표시하는 방법을 단계별로 알아봅니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

다음 코드를 res/layout/activity_main.xml 파일에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/dateView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="20dp"
        android:text="Set the Date"
        android:textColor="@android:color/background_dark"
        android:textStyle="bold" />
    <CalendarView
        android:id="@+id/calender"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </CalendarView>
</RelativeLayout>

이 레이아웃에는 선택된 날짜를 표시할 TextView와 화면 중앙에 배치되는 CalendarView가 포함되어 있습니다.

3단계: MainActivity 작성

다음 코드를 src/MainActivity.java 파일에 추가합니다.

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CalendarView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    CalendarView calendar;
    TextView dateView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        calendar = findViewById(R.id.calender);
        dateView = findViewById(R.id.dateView);
        calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                String Date = dayOfMonth + "-" + (month + 1) + "-" + year;
                dateView.setText(Date);
            }
        });
    }
}

핵심은 setOnDateChangeListener() 메서드입니다. 사용자가 캘린더에서 날짜를 선택하면 onSelectedDayChange() 콜백이 호출되며, 이때 전달받은 연도(year), 월(month), 일(dayOfMonth) 값을 조합해 TextView에 날짜 문자열로 표시합니다. 참고로 month 값은 0부터 시작하므로 실제 월을 표시하려면 1을 더해야 합니다.

4단계: AndroidManifest.xml 설정

다음 코드를 androidManifest.xml 파일에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭합니다. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 캘린더가 표시됩니다.

Android 앱에서 CalendarView 클래스를 활용한 캘린더 위젯 구현 방법

캘린더에서 원하는 날짜를 탭하면 상단의 TextView에 선택한 날짜가 "일-월-연도" 형식으로 즉시 업데이트되는 것을 확인할 수 있습니다.