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

안드로이드에서 커스텀 다이얼로그(Custom Dialog) 만드는 방법

이 튜토리얼에서는 안드로이드 앱에서 커스텀 메시지 다이얼로그를 만들어 화면에 표시하는 방법을 단계별로 알아봅니다. 기본 AlertDialog에 직접 디자인한 레이아웃을 적용하여 입력창과 버튼을 자유롭게 구성하는 실전 예제입니다.

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">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="My Custom Message"
        android:textSize="22sp"
        android:textAlignment="center"
        android:layout_marginTop="30dp"
        android:id="@+id/myCustommessage"/>
    <Button
        android:layout_width="140dp"
        android:layout_height="80dp"
        android:layout_centerInParent="true"
        android:text="Show Message"
        android:backgroundTint="@color/colorPrimary"
        android:textSize="20dp"
        android:textColor="#ffffff"
        android:onClick="btn_showMessage" />
</RelativeLayout>

메인 화면에는 중앙에 'Show Message' 버튼 하나와 상단에 커스텀 메시지를 표시할 TextView가 배치됩니다.

3단계 — 커스텀 다이얼로그 레이아웃 파일 생성

프로젝트 창에서 res → layout 폴더를 마우스 오른쪽 버튼으로 클릭한 후 New → Layout Resource File을 선택합니다. 파일 이름을 custom_dialog으로 지정하고, Root element에 LinearLayout을 입력한 뒤 OK를 클릭합니다.

4단계 — custom_dialog.xml 코드 작성

방금 생성한 custom_dialog.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enter your Message"
        android:textSize="22sp"
        android:textAlignment="center" />
    <EditText
        android:id="@+id/txt_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="Enter your Message"
        android:textSize="20sp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:text="Cancel"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_weight="1"
            android:id="@+id/btn_cancel"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:text="Okay"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_weight="1"
            android:id="@+id/btn_okay"/>
    </LinearLayout>
</LinearLayout>

이 레이아웃은 다이얼로그에 표시될 제목 텍스트, 사용자 입력을 받을 EditText, 그리고 Cancel과 Okay 두 개의 버튼으로 구성되어 있습니다.

5단계 — MainActivity.java 코드 작성

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

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    TextView myCustomMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myCustomMessage = (TextView)findViewById(R.id.myCustommessage);
    }
    public void btn_showMessage(View view){
        final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        View mView = getLayoutInflater().inflate(R.layout.custom_dialog,null);
        final EditText txt_inputText = (EditText)mView.findViewById(R.id.txt_input);
        Button btn_cancel = (Button)mView.findViewById(R.id.btn_cancel);
        Button btn_okay = (Button)mView.findViewById(R.id.btn_okay);
        alert.setView(mView);
        final AlertDialog alertDialog = alert.create();
        alertDialog.setCanceledOnTouchOutside(false);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        btn_okay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myCustomMessage.setText(txt_inputText.getText().toString());
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }
}

여기서 핵심은 getLayoutInflater().inflate()를 사용해 custom_dialog 레이아웃을 AlertDialog에 연결하는 부분입니다. Okay 버튼을 누르면 입력한 텍스트가 메인 화면의 TextView에 반영되고, Cancel 버튼을 누르면 다이얼로그가 닫힙니다. 또한 setCanceledOnTouchOutside(false)를 설정해 다이얼로그 바깥 영역을 터치해도 닫히지 않도록 했습니다.

6단계 — AndroidManifest.xml 확인

androidManifest.xml 파일에 아래와 같이 MainActivity가 등록되어 있는지 확인합니다.

<?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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 기기에서 앱이 실행되면 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 커스텀 다이얼로그(Custom Dialog) 만드는 방법

'Show Message' 버튼을 누르면 커스텀 다이얼로그가 나타나고, 메시지를 입력한 뒤 Okay를 누르면 입력 내용이 메인 화면에 출력됩니다.

안드로이드에서 커스텀 다이얼로그(Custom Dialog) 만드는 방법