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

Android 알림에서 텍스트 마키(흐르는 글자) 효과 구현하는 방법

Android 알림에서 텍스트 마키(흐르는 글자) 효과 구현하는 방법

이 튜토리얼에서는 Android 알림(Notification)의 텍스트 콘텐츠에 마키(Marquee) 효과를 적용하는 방법을 단계별로 살펴봅니다. 마키 효과란 텍스트가 화면을 가로질러 계속 흐르듯 움직이는 애니메이션으로, 알림 영역처럼 좁은 공간에서 긴 텍스트를 끊김 없이 보여주고 싶을 때 유용하게 활용됩니다.

핵심 아이디어는 간단합니다. 커스텀 알림 레이아웃을 만들고, TextView에 android:ellipsize="marquee" 속성과 android:singleLine="true" 속성을 함께 지정하는 것입니다.

1단계 — 새 프로젝트 생성

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

2단계 — activity_main.xml 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 알림을 생성하는 버튼 하나를 배치하는 간단한 레이아웃입니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: tools = "https://schemas.android.com/tools"
   android :layout_width = "match_parent"
   android :layout_height = "match_parent"
   tools :context = ".MainActivity" >
   <Button
      android :layout_width = "match_parent"
      android :layout_height = "wrap_content"
      android :layout_centerInParent = "true"
      android :layout_margin = "16dp"
      android :onClick = "createNotification"
      android :text= "create notification" />
</RelativeLayout>

3단계 — custom_notification_layout.xml 작성

알림에 사용할 커스텀 레이아웃 파일인 res/layout/custom_notification_layout.xml을 생성하고 아래 코드를 추가합니다.

여기서 주목할 부분은 하단의 TextView입니다. android:ellipsize="marquee"android:singleLine="true" 속성을 함께 설정하면 텍스트가 한 줄로 제한되며, 화면 폭을 초과하는 내용이 흐르는 애니메이션으로 표시됩니다. 아이콘 역할을 하는 ImageView와 제목용 TextView도 함께 배치했습니다.

<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "https://schemas.android.com/apk/res/android"
   android :id = "@+id/layout"
   android :layout_width = "fill_parent"
   android :layout_height = "64dp"
   android :padding = "10dp" >
   <ImageView
      android :id = "@+id/image"
      android :layout_width = "wrap_content"
      android :layout_height = "fill_parent"
      android :layout_alignParentStart = "true"
      android :layout_marginEnd = "10dp"
      android :contentDescription = "@string/app_name"
      android :src = "@mipmap/ic_launcher" />
   <TextView
      android :id = "@+id/title"
      android :layout_width = "wrap_content"
      android :layout_height = "wrap_content"
      android :layout_toEndOf = "@id/image"
      android :text = "Testing"
      android :textColor = "#000"
      android :textSize = "13sp" />
   <TextView
      android :id = "@+id/text"
      android :layout_width = "wrap_content"
      android :layout_height = "wrap_content"
      android :layout_below = "@id/title"
      android :layout_toEndOf = "@id/image"
      android :ellipsize = "marquee"
      android :singleLine = "true"
      android :text = "Lorem Ipsum is simply dummy text of the printing and typesetting
         industry. Lorem Ipsum has been the industry's standard dummy text ever since the
         1500s, when an unknown printer took a galley of type and scrambled it to make a type
         specimen book. It has survived not only five centuries, but also the leap into
         electronic typesetting, remaining essentially unchanged. It was popularised in the
         1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more
         recently with desktop publishing software like Aldus PageMaker including versions of
         Lorem Ipsum. "
      android :textColor = "#000"
      android :textSize = "13sp" />
</RelativeLayout>

4단계 — MainActivity 코드 작성

src/MainActivity 파일에 아래 코드를 추가합니다. RemoteViews를 사용해 위에서 만든 커스텀 레이아웃을 알림 콘텐츠로 지정하고, Android 8.0(오레오, API 26) 이상에서는 반드시 알림 채널(Notification Channel)을 생성해야 하므로 버전 분기 처리를 포함했습니다.

package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.RemoteViews ;
public class MainActivity extends AppCompatActivity {
   public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
   private final static String default_notification_channel_id = "default" ;
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
   }
   public void createNotification (View view) {
      RemoteViews contentView = new RemoteViews(getPackageName() , R.layout. custom_notification_layout ) ;
      NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
      mBuilder.setContent(contentView) ;
      mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
      mBuilder.setAutoCancel( true ) ;
      if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
         int importance = NotificationManager. IMPORTANCE_HIGH ;
         NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
         mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
         assert mNotificationManager != null;
         mNotificationManager.createNotificationChannel(notificationChannel) ;
      }
      assert mNotificationManager != null;
      mNotificationManager.notify(( int ) System. currentTimeMillis () ,
      mBuilder.build()) ;
   }
}

5단계 — AndroidManifest.xml 설정

AndroidManifest.xml 파일에 아래 코드를 추가합니다. 진동 권한(VIBRATE)을 선언하고, MainActivity를 앱 실행 시 시작되는 런처 액티비티로 등록합니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns:
   android = "https://schemas.android.com/apk/res/android" package= "app.tutorialspoint.com.notifyme">
   <uses-permission
      android :name= "android.permission.VIBRATE" />
        <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 아이콘을 클릭하세요. 기기 선택 목록에서 자신의 모바일 기기를 고르면 앱이 설치·실행되고 기본 화면이 표시됩니다.

화면 중앙의 create notification 버튼을 누르면 알림이 생성되며, 알림의 본문 텍스트가 한 줄로 계속 흐르는 마키 효과가 정상적으로 적용된 것을 확인할 수 있습니다.