ユーザ用ツール

ダイアログの中でContextMenuを使う

概要

ダイアログの中に、ListViewなどの要素を置いて、コンテキストメニューを使って制御をしたい。 そういう場合、通常のActivityで行っているように、OnCreateContextMenu()とOnContextItemSelected()を実装しても、メニュー選択の処理がされない。

ここでは、メニューを作成し、適切にコールバックを受け取る方法について説明する。

ダイアログクラスの作成

class MyDialog extends Dialog implements OnClickLisener

のように、Dialogを継承し、OnClickListenerを実装したクラスを宣言する。

コンテキストメニューの登録

Listview listView;

registerForContextMenu(listView);
listView.setOnCreateContextMenuListener(this);

registerForContextMenuの後に、setOnCreateContextMenuListener()をする。ここが、Activityの場合との違いのまず第一点目である。

コンテキストメニューの作成

これは、通常通り OnCreateContextMenu()で行う。

コンテキストメニュー選択後の処理

Activityでやるように、OnContextItemSelected()を実装しても、ここに処理が渡されることはない。 代わりに、

boolean onMenuItemSelected(int featureId, MenuItem item)

を実装してやる。ここが、もう一点の相違である。 あとは、通常 OnContextItemSelected()で行っているように処理を行えば良い。

Androidに関してへ戻る。

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also, you acknowledge that you have read and understand our Privacy Policy. If you do not agree, please leave the website.

More information