java - 如何创建 float 上下文菜单?

标签 java android

我想在单击按钮时打开一个菜单。我尝试创建一个 float 上下文菜单,但是当我按下按钮时没有任何反应。

主 Activity .java

public class MainActivity extends ListActivity {

    private Button button1;

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

        button1 = (Button)findViewById(R.id.button1);

        registerForContextMenu(button1);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.item1:
                function();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

主.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.prounitconverter.prounitconverter.MainActivity" >

    <item android:id="@+id/item1"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

另外,我如何为两个不同的按钮创建两个菜单?

最佳答案

如果您正在寻找简单的下拉菜单 - 使用 PopupMenu :

//anchorView - any view, where you want show menu
PopupMenu popupMenu = new PopupMenu(anchorView.getContext(), anchorView);
popupMenu.inflate(R.menu.my_menu_xml);
popupMenu.show();

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

相关文章:

java - ArrayList 类型不匹配

java - 如何使用 Spring MVC Controller 返回 html 文件

android - 如何在 CLI 5.2/PGB 下使用 phonegap-facebook-plugin

java - 如何创建带有阴影和垂直项目的 CardView

android - 水平格子线android textview

java - 自定义适配器ListView错误

java - HiveDriver 类NotFoundException

java - 如何从其他上下文调用 Java 类

java - Android 图像上的文字

android - 方法 View.getForeground() 需要 api 23