如何以编程方式打开上下文菜单?

时间:2012-12-01 17:31:32

标签: android contextmenu

我需要在oncreate方法中打开上下文菜单。 我做了什么:

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        cont = new CustomViewContainer(this);
        setContentView(cont);

        this.openContextMenu(cont);
    }
    @Override  
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {  
        super.onCreateContextMenu(menu, v, menuInfo);  
        menu.setHeaderTitle("Select");  
        menu.add(0, v.getId(), 0, "a");  
        menu.add(0, v.getId(), 0, "b");
        menu.add(0, v.getId(), 0, "c");  
    }
}

但我没看到菜单。求救!

1 个答案:

答案 0 :(得分:3)

根据the openContextMenu(View) documentation,您必须先致电registerForContextMenu(View)

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    cont = new CustomViewContainer(this);
    setContentView(cont);

    registerForContextMenu(cont);
    openContextMenu(cont);
}