单击上下文菜单 Android

Context menu single click Android

我是 Android 开发的新手。我试图向我的应用程序添加上下文菜单。我知道默认情况下需要长按按钮才能打开上下文菜单。但我需要让它在单击时出现。我在 Whosebug 中尝试了所有其他解决方案,但其中 none 确实对我有帮助。

我已经在下面发布了我的代码。请告诉我需要做哪些修改才能使其正常工作。

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
    }
}
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 
    } 
} 

你可以简单地写:

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