Calling a context menu when onClickListener is applied to an action

Please find the sample code below:

    public class Abc extends Activity implements OnClickListener{

    private ListView displayList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainlayout);

        displayList =(ListView)findViewById(R.id.addressbooklistview);
        addressbookAdapter = new CustomListAdapter(this,addressbookList);
        displayList.setAdapter(addressbookAdapter);

        registerForContextMenu(displayList);

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) 
    { 
         Log.e("", "Entered Context Menu");
    }

    public void onClick(View v) {

        Log.e("", "Click Detected");
    }

}

I can not call the context menu with a long press. Please let me know any solution for this.

+3
source share
2 answers

I had this problem. Initially, the functionality of the "show context menu" worked, but when I added the normal "click" functionality, the context menu no longer worked.

, onClick() TextView Listview, ListView. , . , , Activity onCreate setOnItemClickListener() ListView. , :

// This creates the context menu functionality.
registerForContextMenu(findViewById(R.id.list_item));

// This creates the click functionality for the listview item.
ListView listView = (ListView) findViewById(R.id.list_item);
listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        // code here            
    }
});
+4

, , longClick OnLongClickHandler :

   view.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View v) {
            // do something
        }
    });
    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return false; // ignore and bubble up
        }
    });
+3

Source: https://habr.com/ru/post/1757797/


All Articles