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

Android 알림에 EditText(텍스트 입력창)를 삽입하는 방법

개요

이 예제는 Android 알림(Notification) 안에 EditText(텍스트 입력창)를 삽입하는 방법을 보여줍니다. RemoteViews와 커스텀 레이아웃을 활용하면 일반적인 텍스트 알림이 아니라, 이미지·제목·텍스트 입력 필드까지 포함된 맞춤형 알림 UI를 만들 수 있습니다.

구현 단계

1단계 — 새 프로젝트 생성

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

2단계 — 메인 레이아웃 작성

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 :onClick = "createNotification"
      android :layout_width = "match_parent"
      android :layout_height = "wrap_content"
      android :layout_centerInParent = "true"
      android :layout_margin = "16dp"
      android :text = "Create notification" />
</RelativeLayout>

3단계 — 커스텀 알림 레이아웃 작성

res/layout/custom_notification_layout.xml 파일을 만들고 다음 코드를 추가합니다. 이 레이아웃은 앱 아이콘(ImageView), 제목(TextView), 그리고 사용자가 텍스트를 입력할 수 있는 EditText로 구성됩니다.

<? 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 = "96dp"
   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 = "18sp" />
   <EditText
      android :layout_width = "match_parent"
      android :layout_height = "wrap_content"
      android :layout_below = "@+id/title"
      android :layout_marginTop = "8dp"
      android :layout_toEndOf = "@+id/image"
      android :hint = "Enter something..."
      android :inputType = "text"
      android :textSize = "14sp" />
</RelativeLayout>

4단계 — MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 핵심은 RemoteViews 객체를 생성해 커스텀 레이아웃을 알림의 콘텐츠로 지정하는 부분입니다. 또한 Android 8.0(Oreo) 이상에서는 알림 채널을 반드시 생성해야 한다는 점도 확인하세요.

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 ) ;
      onNewIntent(getIntent()) ;
   }
   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 파일에 다음 코드를 추가합니다.

<? 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 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android 알림에 EditText(텍스트 입력창)를 삽입하는 방법

참고 사항

알림의 RemoteViews는 보안상의 이유로 TextView, ImageView, Button 등 제한된 종류의 위젯만 완전히 지원합니다. EditText처럼 입력이 필요한 뷰는 기기 버전이나 제조사에 따라 상호작용이 동작하지 않을 수 있으므로, 실제 서비스에서는 사용자 입력이 필요한 경우 알림 탭 시 열리는 액티비티로 처리하는 방식을 권장합니다.