liguofeng29’s blog

個人勉強用ブログだっす。

AndroidのUI - PopupMenu

 

activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show popup menu"
android:onClick="clickBtn"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
 
popup_menu.xml
 
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/search"
android:icon="@android:drawable/ic_menu_search"
android:title="search" />
<item
android:id="@+id/add"
android:icon="@android:drawable/ic_menu_add"
android:title="add" />
<item
android:id="@+id/edit"
android:icon="@android:drawable/ic_menu_edit"
android:title="edit">
<menu>
<item
android:id="@+id/copy"
android:title="copy" />
<item
android:id="@+id/cut"
android:title="cut" />
<item
android:id="@+id/paste"
android:title="paste" />
</menu>
</item>
<item
android:id="@+id/exit"
android:title="hide" />
</menu>
 
MainActivity.java
 
package com.example.liguofeng.popupmenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

public void clickBtn(View view) {
// ①生成
PopupMenu popupMenu = new PopupMenu(this, view);

// ②MenuInflater.inflate()
getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
// callback
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
//Toast.makeText(this, item.getTitle(),Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
// ③表示
popupMenu.show();
}
}