본문 바로가기
안드로이드

[Android] DatePicker

by 엘딘 2022. 3. 28.
activity_main.xml
<TextView
        android:layout_width="333dp"
        android:layout_height="68dp"
        android:text=" HI "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.08"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:id="@+id/textView"/>

<Button
        android:text="날짜 읽어오기 "
        android:layout_width="168dp"
        android:layout_height="53dp"
        android:id="@+id/button"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        android:layout_marginTop="36dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

// 달력 형태를 바꾸기 위해선
// android:datePickerMode="spinner" or "calender"
<DatePicker
        android:id="@+id/datePicker"
        android:layout_width="320dp"
        android:layout_height="430dp"
        android:calendarViewShown="false"
        android:datePickerMode="spinner"
        app:layout_constraintTop_toBottomOf="@+id/button"
        android:layout_marginTop="64dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

 

 

MainActivity
class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var cal = Calendar.getInstance()
        val year = cal.get(Calendar.YEAR)
        val month = cal.get(Calendar.MONTH)
        val dayOfMonth = cal.get(Calendar.DAY_OF_MONTH)

        val textView = findViewById<TextView>(R.id.textView)
        val button = findViewById<Button>(R.id.button)

        textView.text =
                        """
                            초기 설정된 날짜 [월/일/년도]
                            $year / ${month + 1} / $dayOfMonth
                        """.trimIndent()


        button.setOnClickListener(this)
    }

    override fun onClick(view: View?) {
        val textView = findViewById<TextView>(R.id.textView)
        val datePicker = findViewById<DatePicker>(R.id.datePicker)

	// id가 button인 버튼을 눌렀을때 
        if(view?.id == R.id.button){

            textView.text = "초기 설정된 날짜 [월/일/년도] : \n" + datePicker.year.toString() + "/" +
                    "" + (datePicker.month + 1).toString() + "/" + datePicker.dayOfMonth.toString()

        }
    }
}

'안드로이드' 카테고리의 다른 글

[Android] File(추후 작성)  (0) 2022.03.31
[Android] Clock  (0) 2022.03.28
[Android] RatingBar  (0) 2022.03.28
[Android] seekbar  (0) 2022.03.28
[Android] 서버에 저장된 이미지 가져오기  (0) 2022.03.28

댓글