728x90
안녕하세요,
오늘은 BottomSheet에 CalendarView띄워서 날짜를 선택하는 예제를 만들어보도록 하겠습니다.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button btnShowBottomSheet;
private TextView tvMainSelectedDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowBottomSheet = findViewById(R.id.btn_show_bottom_sheet);
tvMainSelectedDate = findViewById(R.id.tv_main_selected_date);
btnShowBottomSheet.setOnClickListener(view -> showCalendarBottomSheet());
}
private void showCalendarBottomSheet() {
View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_calendar, null);
BottomSheetDialog dialog = new BottomSheetDialog(this);
dialog.setContentView(view);
CalendarView calendarView = view.findViewById(R.id.calendar_view);
TextView text_selectedDate = view.findViewById(R.id.selected_date);
calendarView.setOnDateChangeListener((calendarView1, year, month, dayOfMonth) -> {
String selectedDate = year + "년 " + (month + 1) + "월 " + dayOfMonth + "일";
text_selectedDate.setText("선택한 날짜: " + selectedDate);
// 메인 화면에 반영
tvMainSelectedDate.setText("선택된 날짜: " + selectedDate);
// 바텀시트 닫기
dialog.dismiss();
});
dialog.show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_show_bottom_sheet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="날짜 선택하기" />
<TextView
android:id="@+id/tv_main_selected_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="선택된 날짜 없음"
android:layout_below="@id/btn_show_bottom_sheet"
android:layout_marginTop="16dp"
android:textSize="18sp" />
</LinearLayout>
bottom_sheet_calendar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/bottom_sheet_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/selected_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="선택한 날짜:"
android:textSize="16sp"
android:layout_marginBottom="12dp" />
<CalendarView
android:id="@+id/calendar_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
시연 영상입니다.
'안드로이드 자바' 카테고리의 다른 글
[Java][Android]Web3j 활용해 지갑 주소 생성하기 (0) | 2025.04.11 |
---|---|
[Java][Android] Timer 클래스 활용해 카운트 작업 하기 (0) | 2025.04.08 |
[Java][Android]Web3j 활용해 키쌍 생성하기 (0) | 2025.04.04 |
[Java][Android] MotionLayout 활용하기 (0) | 2025.04.01 |
[Java][Android] ChipGroup에 Chip 동적 추가하기 (+ 버튼) (0) | 2025.03.30 |