Android Kotlin : 현재 시간 표시하기(Text Clock)

2022. 8. 3. 18:36[Android APP] feat. Kotlin/Kotlin 공부

개요

안드로이드에서 현재 시간을 나타내는 방법은 여러가지가 있다.

이번엔 그 방법 중 가장 쉬운(?) 안스에서 제공해주는 위젯인 "Text Clock"을 사용해보려한다.

 

 

코드

1. xml

예제이기 때문에 xml에 간단하게 Text Clock을 추가해주겠다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TextClock
        android:id="@+id/textclock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textColor="@color/black"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

2. Activity

Text Clock에 자신이 원하는 포맷 형식으로 맞춰준다.

(format12Hour = 12시간 기준, format24Hour = 24시간 기준)

 binding.textclock.format12Hour

 

3. 그러면 현재 시각에 맞춰서 Text Clock에 현재 시각을 표시해준다.

요론 식으로 ㅎㅎ

 

4. 만약 날짜와 초 단위도 표시해주고 싶다면 아래 코드로 교체해보자!

 binding.textclock.format12Hour = "yyyy-MM-dd a hh:mm:ss"

날짜 형식을 자기가 커스텀 해서 표시할 수 있다.

 

 

 

안드로이드 핸드폰 기계 시스템 시간을 불러오는 방식도 있고, API로 현재 시간을 쏴주는 방식도 있지만 

이렇게 간단하게 표현할 수 있는 기능도 있으니 참고하길 바란다!

이상!

반응형