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

【Android】アラートダイアログを画面サイズの50%に表示する方法

このチュートリアルでは、Androidアプリでアラートダイアログを画面サイズの50%の大きさで表示する方法を解説します。ダイアログの幅と高さを画面の半分に調整できるようになると、UIデザインの自由度が高まり、さまざまな場面で活用できます。

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

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

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xml に以下のコードを追加します。タップするとアラートダイアログを表示するボタンを1つ配置しています。

<?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/btnAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert Dialog"
        android:layout_gravity="top|center_horizontal"
        tools:ignore="MissingConstraints" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

手順3:MainActivity.javaを実装する

src/MainActivity.java に以下のコードを追加します。ボタンがクリックされるとアラートダイアログを表示し、その後 DisplayMetrics で画面サイズを取得して、ダイアログの幅・高さをそれぞれ画面の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.btnAlert);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // アラートダイアログを作成して表示
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setTitle("Say Hello!");
                builder.setMessage("Are you want to say it?");
                builder.setPositiveButton("Say", null);
                builder.setNegativeButton("No", 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);
            }
        });
    }
}

コードのポイント

  • 先に show() を呼び出す:ダイアログは表示後にウィンドウ属性を変更できるため、必ず show() を呼び出してからサイズを設定します。
  • DisplayMetrics で画面サイズを取得:widthPixels と heightPixels から画面のピクセル数を取得できます。
  • copyFrom() で属性を引き継ぐ:現在のウィンドウ属性をコピーしてから幅と高さだけを上書きすることで、他の設定を壊さずに済みます。

手順4:AndroidManifest.xmlを確認する

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】アラートダイアログを画面サイズの50%に表示する方法

  1. 【Android】GridLayoutを画面サイズに合わせて表示する方法を実例付きで解説

    この記事では、Androidアプリ開発においてGridLayoutを画面サイズに合わせて表示する方法を、実際のサンプルコードとともに解説します。GridLayoutはボタンや画像などのビューを格子状に整列できる便利なレイアウトですが、端末ごとに異なる画面サイズへどう対応させるかは多くの開発者がつまずきやすいポイントです。以下の手順に沿って進めれば、どの端末でもバランスよく表示されるGridLayoutを実現できます。 ステップ1:Android Studioで新規プロジェクトを作成する まずAndroid Studioを起動し、「File」→「New Project」を選択します。必要な項目

  2. Androidの画面をテレビに映す方法6選!ChromecastからHDMI接続まで徹底解説

    Androidデバイスで見ている動画や画像を、もっと大きな画面で楽しみたいと思ったことはありませんか?Androidの画面をテレビやPCにキャスト(ミラーリング)すれば、大画面での視聴が実現します。一部の方法ではAndroidデバイスがMiracastに対応している必要がありますが、選択肢はそれだけではありません。この記事では、初心者でも簡単にできる6つの方法を詳しく解説します。YouTubeやNetflixなどの動画を、快適な大画面で楽しんでみましょう。1. Chromecastを使うGoogleが推奨しているのは、Chromecastを使ったキャスト方法です。お使いのAndroidデバイス