答案 0 :(得分:3)
To create POPUp menu on button click:
list_item.xml:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="62dp"
android:layout_marginTop="50dp"
android:text="Show Popup" />
它包含三个项目,如下所示。它在res / menu目录中创建。文件:poupup_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/one"
android:title="PlayNext"/>
<item
android:id="@+id/two"
android:title="AddtoPlayList"/>
<item
android:id="@+id/three"
android:title="Add to Queue"/>
</menu>
按钮单击时显示弹出菜单。文件:MainActivity.java
private Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(
MainActivity.this,
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT
).show();
return true;
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
}