gpt4 book ai didi

android - 如何在上下文菜单中创建弹出菜单?

转载 作者:行者123 更新时间:2023-11-29 00:53:32 24 4
gpt4 key购买 nike

我想为上下文菜单创建一个弹出菜单,这样当我长按上下文菜单时,它会显示另一个弹出菜单。

这是我为上下文菜单编写的代码

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.btn)
registerForContextMenu(button)
}

override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menu?.setHeaderTitle("Choose one")
menu?.add(0, v?.getId()!!, 0, "Upload")
menu?.add(0, v?.getId()!!, 0, "Search")
menu?.add(0, v?.getId()!!, 0, "Share")
}

override fun onContextItemSelected(item: MenuItem): Boolean {

return super.onContextItemSelected(item)
}

最佳答案

在 Java 中,当我长按按钮时它显示上下文菜单,然后我选择上下文菜单它显示弹出菜单。

Button button = findViewById(R.id.button);
registerForContextMenu(button);

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Upload");
menu.add(0, v.getId(), 0, "Search");
menu.add(0, v.getId(), 0, "Share");
menu.add(0, v.getId(), 0, "Bookmark");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
try {
showPopup(findViewById(item.getItemId()));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}

private void showPopup(View anchorView) {
PopupMenu popup = new PopupMenu(this, anchorView);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MapsActivity.this, "Selected Item: "
+ item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.inflate(R.menu.menu_example);
popup.show();
}

关于android - 如何在上下文菜单中创建弹出菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57193358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com