본문 바로가기

소소한 코딩 이야기/Android

Date Picker Dialog에서 선택 날짜 제한하기

Date Picker Dialog를 추가 후,  이번에는 날짜에 제한을 주어 start date 를 선택 하면 end date 선택 시 start date 보다

이전 날짜는 선택할 수 없도록 코드를 추가 해보았습니다.

 

1. Start Date

	//선택 된 start date를 담아줄 변수 선언
	private lateinit var selectedDay: Calendar

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_contents)
        
        //start date
        start_date_btn.setOnClickListener {
            val datePickerDialog = DatePickerDialog(this, { _, year, month, day ->
                //선택한 날짜를 담아준다
                selectedDay = Calendar.getInstance().apply { set(year, month, day) }
				
                ...
                
            }, year, month, day)
            datePickerDialog.show()
        }

 

2. End Date

        end_date_btn.setOnClickListener {
            val datePickerDialog = DatePickerDialog(this, { _, year, month, day ->
                ...
            }, year, month, day).apply {
            	//위에서 저장한 값을 datePicker의 minDate로 적용
                datePicker.minDate = selectedDay.timeInMillis
            }
            datePickerDialog.show()
        }

 

3. 결과화면

 

 

 

※참고사이트※

https://zion830.tistory.com/75

 

[Andoird] DatePicker에서 선택 가능한 날짜 범위 정하기

안드로이드에서 사용자가 날짜를 선택할 수 있도록 DatePicke나 DatePickerDialog를 사용한다. 달력은 직접 만들려면 손이 많이 가서 잠깐 보여주는 용도면 거의 다 기본 뷰를 쓰는거 같다. 이미 지나간

zion830.tistory.com