📅  最后修改于: 2023-12-03 15:29:22.747000             🧑  作者: Mango
Android中的弹出菜单是一种常见的用户界面元素,可以在用户点击某个控件时,弹出一个菜单选项供用户选择。
<Button
android:id="@+id/button_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Menu"
/>
Button buttonMenu = findViewById(R.id.button_menu);
buttonMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO: 弹出菜单
}
});
PopupMennu popupMenu = new PopupMenu(this, buttonMenu);
popupMenu.getMenuInflater().inflate(R.menu.menu_main, popupMenu.getMenu());
popupMenu.show();
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_copy"
android:title="Copy" />
<item
android:id="@+id/action_cut"
android:title="Cut" />
<item
android:id="@+id/action_paste"
android:title="Paste" />
</menu>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonMenu = findViewById(R.id.button_menu);
buttonMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, buttonMenu);
popupMenu.getMenuInflater().inflate(R.menu.menu_main, popupMenu.getMenu());
popupMenu.show();
}
});
}
}