Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】デフォルトのAlertDialog(アラートダイアログ)の高さと幅を制御する方法

この記事では、Androidアプリにおける標準のAlertDialog(アラートダイアログ)の高さと幅を制御する方法を、実際のサンプルコードとともにステップ形式で解説します。ダイアログを画面いっぱいに表示したい場合や、独自のレイアウトサイズに調整したい場合に役立つテクニックです。

実装のポイント

AlertDialogのサイズを変更するには、show()メソッドでダイアログを表示した後に、WindowManager.LayoutParamsを使用してウィンドウ属性を上書きします。この処理は必ずalertDialog.show()の後に行う必要がある点に注意してください。

Step 1:新規プロジェクトを作成する

Android Studioを開き、「File → New Project」から新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトのセットアップを完了させてください。

Step 2:activity_main.xml にレイアウトを記述する

res/layout/activity_main.xml に以下のコードを追加します。ここでは、中央に配置されたボタンを1つ設置し、タップするとアラートダイアログが表示されるシンプルな構成にしています。

<?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"
    android:id="@+id/relativeLayout"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Dialog"
        android:layout_centerInParent="true" />
</RelativeLayout>

Step 3:MainActivity.java にダイアログ表示処理を記述する

src/MainActivity.java に以下のコードを追加します。ボタンがクリックされるとAlertDialogを生成・表示し、その直後にWindowManager.LayoutParamsを使ってダイアログの幅と高さをMATCH_PARENT(画面いっぱい)に変更しています。

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
    public class MainActivity extends AppCompatActivity{
        Button button;
        RelativeLayout relativeLayout;
        Context context;
        Activity myActivity;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            relativeLayout = findViewById(R.id.relativeLayout);
            context = getApplicationContext();
            button = findViewById(R.id.button);
            myActivity = MainActivity.this;
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
                builder.setTitle("My Action Bar");
                builder.setMessage("This is my custom Action bar, do you like it?");
                builder.setPositiveButton("Yes", null);
                builder.setNegativeButton("No", null);
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                layoutParams.copyFrom(alertDialog.getWindow().getAttributes());
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
                alertDialog.getWindow().setAttributes(layoutParams);
            }
        });
    }
}

なお、画面いっぱいではなく任意のサイズにしたい場合は、MATCH_PARENTの代わりにlayoutParams.width = 800;のようにピクセル値(px)を直接指定することも可能です。

Step 4:AndroidManifest.xml を確認する

androidManifest.xml には以下のコードを記述します。通常、Android Studioが自動生成する内容とほぼ同じですが、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スマートフォンをパソコンに接続していることを前提に説明します。

Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開いた状態で、ツールバーにある「Run」アイコンをクリックします。接続済みのモバイル端末を選択すると、端末側にアプリの初期画面が表示されます。

【Android】デフォルトのAlertDialog(アラートダイアログ)の高さと幅を制御する方法

初期画面の中央にあるボタンをタップすると、画面全体に広がるカスタムサイズのアラートダイアログが表示されます。これで、AlertDialogの高さと幅が正しく制御できていることが確認できます。

【Android】デフォルトのAlertDialog(アラートダイアログ)の高さと幅を制御する方法

  1. Androidでアラートダイアログを表示する方法【初心者向けサンプルコード付き】

    Androidでアラートダイアログ(AlertDialog)を表示する方法このチュートリアルでは、Androidアプリでアラートダイアログを表示する方法を解説します。サンプルとして、戻るボタンが押されたタイミングで「本当に終了しますか?」という確認ダイアログを表示する実装を紹介します。アプリの誤操作による終了を防ぎたい場合などに役立つ、定番のテクニックです。手順1:Android Studioで新規プロジェクトを作成するまず、Android Studioを起動し、メニューから File → New Project を選択します。必要な項目(プロジェクト名、パッケージ名、保存場所など)を入力して

  2. AndroidでImageViewの幅と高さを取得する方法【サンプルコード付き】

    この記事では、Androidアプリ開発において android.widget.ImageView の幅(width)と高さ(height)を取得する方法を、実際に動作するサンプルコードとともにステップごとに解説します。実装の全体像ImageViewのサイズを取得するには、getWidth() メソッドと getHeight() メソッドを使用します。ここでは、ボタンをタップしたときにImageViewのサイズを取得し、TextViewに結果を表示するシンプルなサンプルアプリを作成します。手順1:新しいプロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New