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

Android에서 알림 대화상자(AlertDialog)를 화면 크기의 50%로 설정하는 방법

개요

이 튜토리얼에서는 Android 앱에서 알림 대화상자(AlertDialog)가 화면 크기의 정확히 50%를 차지하도록 크기를 조절하는 방법을 단계별로 살펴봅니다. 기본적으로 AlertDialog는 내용에 맞게 자동으로 크기가 조정되지만, WindowManager.LayoutParams를 활용하면 원하는 비율로 직접 설정할 수 있습니다.

구현 단계

1단계 − 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택하고 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다. 언어는 Java를 기준으로 진행합니다.

2단계 − 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 버튼 하나를 배치하여 클릭 시 알림 대화상자가 표시되도록 구성합니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    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"
    android:fitsSystemWindows="true"
    android:id="@+id/coordinator_layout"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_alert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알림 대화상자 표시"
        android:layout_gravity="top|center_horizontal"
        tools:ignore="MissingConstraints" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

3단계 − MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 핵심 로직은 다음과 같습니다.

  • DisplayMetrics로 기기의 실제 화면 너비와 높이를 픽셀 단위로 가져옵니다.
  • dialog.show() 호출 후 dialog.getWindow().getAttributes()로 현재 속성을 복사합니다.
  • 화면 크기에 0.5f를 곱해 대화상자의 가로·세로 크기를 각각 50%로 지정합니다.
package com.app.sample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import android.app.AlertDialog;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;
    private CoordinatorLayout mCLayout;
    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = getApplicationContext();
        mActivity = MainActivity.this;
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mButton = (Button) findViewById(R.id.btn_alert);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setTitle("인사하기!");
                builder.setMessage("인사 메시지를 표시할까요?");
                builder.setPositiveButton("예", null);
                builder.setNegativeButton("아니오", null);

                AlertDialog dialog = builder.create();
                dialog.show();

                // 기기 화면 크기 가져오기
                DisplayMetrics displayMetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                int displayWidth = displayMetrics.widthPixels;
                int displayHeight = displayMetrics.heightPixels;

                // 대화상자 크기를 화면의 50%로 설정
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                layoutParams.copyFrom(dialog.getWindow().getAttributes());
                int dialogWindowWidth = (int) (displayWidth * 0.5f);
                int dialogWindowHeight = (int) (displayHeight * 0.5f);
                layoutParams.width = dialogWindowWidth;
                layoutParams.height = dialogWindowHeight;

                dialog.getWindow().setAttributes(layoutParams);
            }
        });
    }
}

참고: 반드시 dialog.show()를 먼저 호출한 후 창 속성을 변경해야 합니다. show() 전에 속성을 설정하면 getWindow()가 null을 반환하거나 크기가 적용되지 않을 수 있습니다.

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(실행) 아이콘을 클릭하고, 실행 옵션에서 연결된 모바일 기기를 선택하세요. 그러면 앱이 설치되어 실행되며, 기본 화면이 표시됩니다.

화면 상단의 버튼을 누르면 알림 대화상자가 나타나는데, 이때 대화상자가 화면 전체가 아닌 정확히 50% 크기로 표시되는 것을 확인할 수 있습니다.

Android에서 알림 대화상자(AlertDialog)를 화면 크기의 50%로 설정하는 방법

마무리

이처럼 WindowManager.LayoutParams를 사용하면 AlertDialog의 크기를 화면 비율에 맞게 유연하게 조절할 수 있습니다. 0.5f 값을 다른 숫자로 바꾸면 30%, 80% 등 원하는 비율로 자유롭게 응용할 수 있으니 참고하세요.