Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android Toast 표시 시간을 Toast.LENGTH_LONG보다 길게 설정하는 방법

Android에서 Toast는 짧은 메시지를 화면 하단에 잠깐 표시하는 데 널리 사용되는 UI 요소입니다. 하지만 기본 제공 옵션인 Toast.LENGTH_SHORT(약 2초)와 Toast.LENGTH_LONG(약 3.5초)만 사용할 수 있어, 그 이상 메시지를 유지하고 싶을 때는 별도의 방법이 필요합니다.

이 글에서는 CountDownTimer를 활용하여 Toast의 표시 시간을 원하는 만큼 길게 설정하는 방법을 단계별로 살펴봅니다.

핵심 원리

Toast API는 직접적으로 표시 시간을 지정할 수 없기 때문에, 일정 간격마다 show()를 반복 호출하여 Toast가 화면에 계속 나타나도록 하는 방식을 사용합니다. 아래 예제에서는 10초 동안 1초 간격으로 Toast를 갱신합니다.

구현 단계

1단계 — 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 필요한 정보를 모두 입력합니다.

2단계 — 레이아웃 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
   xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:app="https://schemas.android.com/apk/res-auto"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
   <androidx.appcompat.widget.AppCompatButton
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:onClick="showToast"/>
</androidx.constraintlayout.widget.ConstraintLayout>

3단계 — MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다.

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   private Toast mToastToShow;
   public void showToast(View view) {
      int toastDurationInMilliSeconds = 10000;
      mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);
      CountDownTimer toastCountDown;
      toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
         public void onTick(long millisUntilFinished) {
            mToastToShow.show();
         }
         public void onFinish() {
            mToastToShow.cancel();
         }
      };
      mToastToShow.show();
      toastCountDown.start();
   }
}

위 코드에서 toastDurationInMilliSeconds 값을 변경하면 Toast가 표시되는 총 시간을 자유롭게 조절할 수 있습니다. 예를 들어 30000으로 설정하면 30초간 메시지가 유지됩니다.

4단계 — 매니페스트 설정

Manifests/AndroidManifest.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run 아이콘을 클릭하세요. 실행 대상 목록에서 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 표시됩니다.

Android Toast 표시 시간을 Toast.LENGTH_LONG보다 길게 설정하는 방법

버튼을 누르면 Toast 메시지가 나타나고, 기본 3.5초보다 훨씬 긴 10초 동안 화면에 유지되는 것을 확인할 수 있습니다.