上下文菜单单击Android

时间:2015-11-02 15:09:44

标签: android contextmenu android-contextmenu

我是Android开发的新手。我试图在我的应用程序中添加一个上下文菜单。据我所知,默认情况下需要长按按钮才能打开上下文菜单。但我需要让它出现在单击上。我在stackoverflow中尝试了所有其他解决方案,但它们都没有真正帮助我。

我在下面发布了我的代码。请让我知道要使其发挥作用的修改是什么。

public class ThirdActivity extends ActionBarActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.third_layout);
        confirmButton = (Button) findViewById(R.id.confirmButton);
        registerForContextMenu(confirmButton);
}

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Select Menu");
    menu.add(0, v.getId(), 0, "Action 1");
}


public boolean onContextItemSelected(MenuItem item) {

      if (item.getTitle() == "Action 1") {
        //do something
    }
}

2 个答案:

答案 0 :(得分:5)

just :

public class ThirdActivity extends ActionBarActivity { 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.third_layout);
        confirmButton = (Button) findViewById(R.id.confirmButton);
    confirmButton .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            confirmButton .performLongClick();
        }
    });
        registerForContextMenu(confirmButton); 
} 

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Select Menu");
    menu.add(0, v.getId(), 0, "Action 1");
} 


public boolean onContextItemSelected(MenuItem item) {

      if (item.getTitle() == "Action 1") {
        //do something 
    } 
} 

答案 1 :(得分:0)

你可以简单地写:

 confirmButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.showContextMenu();
        }
    });