본문 바로가기
안드로이드 자바

[Java][Android] TextClock 위젯 사용하기

by teamnova 2025. 3. 4.
728x90

안녕하세요

오늘은 TextClock 위젯을 사용하여 현재 시간을 실시간으로 표시하는것을 구현해보겠습니다.

TextClock을 사용하면 간단하게 구현할 수 있습니다.

 

전체 코드입니다.

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

  private TextClock textClock;
  private boolean is24HourFormat = false; // 초기값: 12시간 형식

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textDate = findViewById(R.id.textDate);
    textClock = findViewById(R.id.textClock);
    Button btnToggleFormat = findViewById(R.id.btnToggleFormat);

    // 현재 날짜 설정
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
    String currentDate = dateFormat.format(new Date());
    textDate.setText(currentDate);

    // 버튼 클릭 시 12시간/24시간 형식 변경
    btnToggleFormat.setOnClickListener(v -> toggleTimeFormat());
  }

  // 시간 형식 변경
  private void toggleTimeFormat() {
    if (is24HourFormat) {
      textClock.setFormat12Hour("a hh:mm:ss");
      textClock.setFormat24Hour("a hh:mm:ss");
    } else {
      textClock.setFormat12Hour("HH:mm:ss");
      textClock.setFormat24Hour("HH:mm:ss");
    }
    is24HourFormat = !is24HourFormat;
  }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:gravity="center"
  android:padding="20dp">

  <!-- 날짜 표시 -->
  <TextView
    android:id="@+id/textDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yyyy/MM/dd"
    android:textSize="18sp"
    android:textColor="@android:color/darker_gray"
    android:layout_marginBottom="10dp"/>

  <!-- 현재 시간 표시 -->
  <TextClock
    android:id="@+id/textClock"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:format12Hour="a hh:mm:ss"
    android:format24Hour="HH:mm:ss"
    android:textSize="32sp"
    android:textColor="@android:color/black"
    android:layout_marginBottom="20dp"/>

  <!-- 12시간/24시간 전환 버튼 -->
  <Button
    android:id="@+id/btnToggleFormat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="표시 방식 전환"/>

</LinearLayout>

 

 

현재 날짜를 SimpleDataFormat을 사용해서 yyyy/MM/dd 형식으로 표시했습니다.

 

그리고 TextClock을 활용해서 실시간으로 시간을 표시하도록 했습니다.

 

12시간 <--> 24시간 형식 변경을 위한 버튼도 추가해주었습니다.

 

이를 활용하면 간단하게 시간을 표시할 수 있어 유용합니다.

 

시연 영상입니다.