Mr Castrovinci
Mr Castrovinci

Reputation: 127

Longclick Issue

I have the following code, which runs when I click on my list, but I need it to only pop up a menu when I long click, the short click does other things.

 @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId()==R.id.listView1) {

            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_list, menu);
        }
    }

@Override
public boolean onContextItemSelected(MenuItem item) {


    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
        case R.id.add:
            // add stuff here
            CreateWO.performClick();
            return true;
        case R.id.punchin:

            final Country country = (Country) ListView1.getItemAtPosition(getwoindex());
            punchin.performClick();
            Toast.makeText(getApplicationContext(), "Work Order="+country.code, Toast.LENGTH_SHORT).show();
            return true;
        case R.id.punchout:
            punchout.performClick();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

Upvotes: 0

Views: 47

Answers (1)

drWisdom
drWisdom

Reputation: 512

For normal click on listView item use: listView.onItemClickListener
and for long click use: listView.setOnItemLongClickListener as follows:

ListView lv =(ListView)findViewById(R.id.my_list); 
----
 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do something
            }
        });

 lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  @Override
  public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //do something on long click
                //like show contextMenu
                return false;
            }
        });

EDIT:

For ContextMenu:
You can either call openContextMenu(view) in your onItemLongClick (as above) OR you can use registerForContextMenu(view), for example:

lv.setAdapter(adapter); 
registerForContextMenu(lv);

By default contextMenu will open when a user long clicks your view. In this case you do not need to call onLongClick manually on the listView.

Upvotes: 1

Related Questions