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

Android 앱에서 커스텀 알림 대화상자(Custom Alert Dialog) 만드는 방법

Android 앱에서 커스텀 알림 대화상자(Custom Alert Dialog) 만드는 방법

이 튜토리얼에서는 Android 앱에서 사용자 지정(커스텀) 알림 대화상자를 만드는 방법을 단계별로 알아봅니다. 안드로이드에서 기본으로 제공하는 AlertDialog 대신 직접 만든 XML 레이아웃을 Dialog에 적용하면, 버튼·이미지·텍스트 등을 자유롭게 배치한 나만의 알림창을 구현할 수 있습니다.

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:id="@+id/activity_main"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="MainActivity">
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/buttonShowCustomDialog"
      android:onClick="exit"
      android:textStyle="normal|bold"
      style="@android:style/Widget.DeviceDefault.Button.Inset"
      android:layout_alignParentBottom="true"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="131dp"
      android:text="Click"/>
   <TextView
      android:text="CLICK TO VIEW CUSTOM ALERT DIALOG"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@+id/buttonShowCustomDialog"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="86dp"
      android:id="@+id/textView"
      android:gravity="center"
      android:textStyle="normal|bold"
      android:textSize="18sp" />
</RelativeLayout>

3단계 — 커스텀 대화상자 레이아웃 생성

새 레이아웃 리소스 파일을 만들고 customdialog.xml에 다음 코드를 작성합니다. 이 레이아웃이 대화상자에 표시될 화면입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent">
   <TextView
      android:text="Alert...!"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/text"
      android:textStyle="normal|bold"
      android:textSize="18sp"
      android:layout_alignParentTop="true"
      android:layout_centerInParent="true"/>
   <ImageButton
      android:layout_width="35dp"
      android:layout_height="35dp"
      app:srcCompat="@drawable/ic_block"
      android:id="@+id/image"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      tools:ignore="ContentDescription,RtlHardcoded" />
   <Button
      android:id="@+id/dialogButtonOK"
      android:layout_width="200dp"
      android:layout_height="wrap_content"
      android:text="Dismiss"
      android:layout_marginTop="23dp"
      android:paddingRight="5dp"
      android:layout_below="@+id/image"
      style="@style/Widget.AppCompat.Button.Colored"
      android:textSize="18sp" />
</RelativeLayout>

4단계 — MainActivity 구현

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

import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
   final Context context = this;
   private Button button;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
         button = findViewById(R.id.buttonShowCustomDialog);
         button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               final Dialog dialog = new Dialog(context);
               dialog.setContentView(R.layout.customdialog);
               Button dialogButton = dialog.findViewById(R.id.dialogButtonOK);
               dialogButton.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                  dialog.dismiss();
                  Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT).show();
               }
            });
            dialog.show();
         }
      });
   }
}

핵심 로직은 간단합니다. Dialog 객체를 생성한 뒤 setContentView()로 위에서 만든 커스텀 레이아웃(customdialog.xml)을 지정하고, show()를 호출하면 대화상자가 화면에 나타납니다. 'Dismiss' 버튼을 클릭하면 dismiss()로 대화상자가 닫히면서 토스트 메시지가 함께 표시됩니다.

5단계 — 매니페스트 설정

androidManifest.xml에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="app.com.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 앱에서 커스텀 알림 대화상자(Custom Alert Dialog) 만드는 방법

Android 앱에서 커스텀 알림 대화상자(Custom Alert Dialog) 만드는 방법 

Android 앱에서 커스텀 알림 대화상자(Custom Alert Dialog) 만드는 방법