Androidアプリ開発

ホーム画面やアプリ画面上に
PopupMenuを表示する

この記事は約22分で読めます。
記事内に広告が含まれています。
スポンサーリンク

この記事はAndroidスマホ用のアプリ開発の中で、
今後の開発で再使用性が高いと思われるコーディングをまとめたものです。
Javaの開発経験、XML構文規則、Androidのアプリ開発経験がある方を対象としています。
Androidのアプリ開発でお役にたててれば、嬉しいです。
(これからAndroidのアプリ開発やJavaでの開発を始めたい方への案内は、
記事の最後で紹介します)

この記事のテーマ


ホーム画面やアプリ画面上にPopupMenuを表示する

ポイント

ユーザに処理を選択させる仕組みとして、PopupMenuは有効な手段のひとつです。
ホーム画面やアプリ画面上にPopupMenuを表示する場合、ForegroundServiceで実装する必要があります。
また、Android11など一部のバージョンでForegroundServiceでPopupMenuが表示できないケースがあります。
今回は、ForegroundServiceでPopupMenuのメニューを表示する実装を紹介します。

ホーム画面上にPopupMenuを表示
アプリ画面上にPopupMenuを表示

ForegroundServiceでPopupMenuを表示する

ForegroundServiceでPopupMenuを表示する場合、WindowManagerでアンカーとなるViewが必要です。
WindowManagerの使用方法はコチラです。

ContextThemeWrapperでスタイルを生成し、アンカーとなるViewを指定してPopupMenuを生成します。
PopupMenuにアイコンを表示する方法はコチラです。

    private PopupMenu popup;
    private List<Launcher> menulist = new ArrayList<>();
    :  

    ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(context, R.style.PopupMenu);
    popup = new PopupMenu(contextThemeWrapper, imageView);
    setForceShowIcon(popup);
    popup.setOnMenuItemClickListener(item -> {
        // メニュー選択の処理
        :
        return false;
    });
    for (int i = 0; i < menulist.size(); i++) {
        popup.getMenu().add(Menu.NONE, i, Menu.NONE, menulist.get(i).title);
        if (menulist.get(i).res > 0) {
            popup.getMenu().getItem(i).setIcon(menulist.get(i).res);
        } else {
            try {
                popup.getMenu().getItem(i).setIcon(icon(menulist.get(i).pkg));
            } catch (PackageManager.NameNotFoundException e) {
                Log.d(TAG, String.format("PopupMenu: %s", e.getMessage()));
            }
        }
    }
    popup.show();
    :

●Launcher

メニューに表示するタイトルやアイコンのリソースIDを管理。

@Entity(tableName = "Launcher", indices = {@Index(value = {"pkg"}, unique = true)})
public class Launcher {
    @PrimaryKey(autoGenerate = true) // シーケンス
    public Integer seq;
    @ColumnInfo(name = "menu")       // メニュー(0/1/2)
    public Integer menu;
    @ColumnInfo(name = "sub")        // サブメニュー(0/1/2/3/4/5)
    public Integer sub;
    @ColumnInfo(name = "res")        // リソース
    public Integer res;
    @ColumnInfo(name = "svc")        // サービス(0/1)
    public Integer svc;
    @ColumnInfo(name = "title")      // タイトル
    public String title;
    @ColumnInfo(name = "pkg")        // パッケージ
    public String pkg;
    @ColumnInfo(name = "cls")        // クラス
    public String cls;
    @ColumnInfo(name = "act")        // アクション
    public String act;
    @ColumnInfo(name = "param")      // パラメータ
    public String param;
    public Launcher(Integer seq, Integer menu, Integer sub, Integer res, Integer svc, String title, String pkg, String cls, String act, String param) {
        this.seq = seq;
        this.menu = menu;
        this.sub = sub;
        this.res = res;
        this.svc = svc;
        this.title = title;
        this.pkg = pkg;
        this.cls = cls;
        this.act = act;
        this.param = param;
    }
}

●Styles.xml

メニューの背景やテキスト色、メニューの表示間隔を設定。

    :
    <style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
        <item name="android:colorBackground">@color/white</item>
        <item name="android:textColor">@color/black</item>
        <item name="android:listPreferredItemHeightSmall">40dp</item>
    </style>
    :

PopupMenuが表示されない場合の対応

Android11など一部のバージョンでForegroundServiceでPopupMenuが表示できないケースがあります。
その場合、PopupMenuをListViewで代用(CustomPopupMenu)します。

●CustomPopupMenu

表示するListViewはWindowManagerで生成します。
visibleメソッドでメニューを開く位置によって、表示位置を調整します。

    :  
    private class CustomPopupMenu {
        android.view.WindowManager windowManager;
        WindowManager.LayoutParams layoutParams;
        ListView listView;
        Context context;
        CustomPopupMenuItemListener customPopupMenuItemListener;
        private CustomPopupMenu(Context context, List<Launcher> arrayList, CustomPopupMenuItemListener customPopupMenuItemListener) {
            windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
            listView = new ListView(context);
            listView.setBackground(context.getDrawable(R.drawable.bg_listview));
            listView.setDivider(null);
            layoutParams = new WindowManager.LayoutParams(
                    0,
                    0,
                    android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT);
            this.context = context;
            this.customPopupMenuItemListener = customPopupMenuItemListener;
            ArrayAdapter arrayAdapter = new ArrayAdapter<>(context, R.layout.item_vertical) {
                @Override
                public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    if (convertView == null) convertView = LayoutInflater.from(context).inflate(R.layout.item_vertical, parent, false);
                    if (!arrayList.get(position).title.isEmpty()) {
                        ImageView icon = convertView.findViewById(R.id.icon);
                        try {
                            if (arrayList.get(position).res > 0) {
                                icon.setImageDrawable(context.getDrawable(arrayList.get(position).res));
                            } else {
                                icon.setImageDrawable(icon(arrayList.get(position).pkg));
                            }
                        } catch (Exception e) {
                            icon.setImageDrawable(null);
                        }
                        TextView title = convertView.findViewById(R.id.title);
                        title.setText(arrayList.get(position).title);
                    }
                    return convertView;
                }
            };
            arrayAdapter.addAll(arrayList);
            listView.setAdapter(arrayAdapter);
            listView.setOnItemClickListener((parent, view, position, id) -> {
                if (customPopupMenuItemListener != null) {
                    customPopupMenuItemListener.doItemClick(parent, view, position, id);
                }
            });
        }
        private Drawable icon(String pkg) throws PackageManager.NameNotFoundException {
            PackageManager packageManager = context.getPackageManager();
            return packageManager.getApplicationIcon(pkg);
        }
        public void visible(Boolean visible) {
            if (listView != null) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (visible) {
                        if (listView.getWindowToken() == null){
                            ListAdapter listAdapter = listView.getAdapter();
                            if (listAdapter == null) { return; }
                            int height = 0;
                            int count = Math.min(listAdapter.getCount(), 10);
                            for (int i = 0 ; i < count ; i++) {
                                View listItem = listAdapter.getView(i, null, listView);
                                listItem.measure(0, 0);
                                height += listItem.getMeasuredHeight();
                            }
                            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
                            int heightPixels = displayMetrics.heightPixels;
                            int style = 0;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                                WindowMetrics windowMetrics = windowManager.getCurrentWindowMetrics();
                                heightPixels = windowMetrics.getBounds().height();
                                style = windowMetrics.getWindowInsets().getInsets(WindowInsets.Type.statusBars()).top + windowMetrics.getWindowInsets().getInsets(WindowInsets.Type.navigationBars()).bottom;
                            }
                            layoutParams.width = (int) (192 * displayMetrics.density);
                            layoutParams.height = height;
                            layoutParams.gravity = Gravity.TOP | Gravity.START;
                            layoutParams.x = Math.min(maid.layoutParams.x, displayMetrics.widthPixels - layoutParams.width);
                            if (maid.layoutParams.y + maid.layoutParams.height < heightPixels - style - layoutParams.height) {
                                layoutParams.y = maid.layoutParams.y + maid.layoutParams.height;
                            } else {
                                layoutParams.y =  Math.min(maid.layoutParams.y - layoutParams.height, heightPixels - style - maid.layoutParams.height - layoutParams.height);
                            }
                            windowManager.addView(listView, layoutParams);
                        }
                    } else {
                        try {
                            windowManager.removeView(listView);
                        } catch (Exception e) {
                            Log.d(TAG, Objects.requireNonNull(e.getMessage()));
                        }
                    }
                });
            }
        }
    }
    :

●item_vertical

アイコンを表示ありのPopupMenuを再現。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@android:color/transparent">
    <FrameLayout
        android:id="@+id/panel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:ignore="UselessParent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:orientation="horizontal>
            <ImageView
                android:id="@+id/icon"
                android:layout_width="32dp"
                android:layout_height="32dp"/>
            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="32dp"
                android:layout_marginStart="4dp"
                android:gravity="center_vertical"
                android:textSize="12sp"/>
        </LinearLayout>
    </FrameLayout>
</LinearLayout>

ListViewで代用したPopupMenu(CustomPopupMenu)を表示します。

    private CustomPopupMenucustomPopupMenu ;
    private List<Launcher> menulist = new ArrayList<>();
    :  

    customPopupMenu = new CustomPopupMenu(context, menulist, (parent, view, position, id) -> {
        // メニュー選択の処理
        :
        customPopupMenu.visible(false);
    });
    customPopupMenu.visible(true);

今回は、ここまでです。

ホーム画面やアプリ画面上にPopupMenuを表示しているAndroidアプリです。

誤字脱字、意味不明でわかりづらい、
もっと詳しく知りたいなどのご意見は、
このページの最後にある
コメントか、
こちらから、お願いいたします♪

ポチッとして頂けると、
次のコンテンツを作成する励みになります♪

ブログランキング・にほんブログ村へ

これからAndroidのアプリ開発やJavaでの開発を始めたい方へ

アプリケーション開発経験がない方や、アプリケーション開発経験がある方でも、JavaやC#などのオブジェクト指向言語が初めての方は、Androidのアプリ開発ができるようになるには、かなりの時間がかかります。
オンラインスクールでの習得を、強くおススメします。

未経験者からプログラマーを目指すのに最適です。まずは無料カウンセリングから♪

ゲーム系に強いスクール、UnityやUnrealEngineを習得するのに最適です。まずは無料オンライン相談から♪

参考になったら、💛をポッチとしてね♪

スポンサーリンク
シェアする
msakiをフォローする
スポンサーリンク

コメント欄

タイトルとURLをコピーしました