Android: Context menu on single click
Here is another simpler way to show context menu on single click.
private void addOnClickListener(){ contactList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { view.showContextMenu(); } })}
replace contactList by your ListView
and make sure to call this method after the initialization of ListView
.
call activity.openContextMenu(l)
onitem click event to open contextmenu on single click and onLongClick call activity.closeContextMenu()
Example
import android.app.Activity;import android.app.ListActivity;import android.content.res.Configuration;import android.os.Bundle;import android.view.ContextMenu;import android.view.ContextMenu.ContextMenuInfo;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemLongClickListener;import android.widget.ArrayAdapter;import android.widget.ListView;public class MyListView extends ListActivity implements OnItemLongClickListener { /** Called when the activity is first created. */ Activity activity = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = this; ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, PENS); setListAdapter(arrayAdapter); getListView().setTextFilterEnabled(true); ListView lv = getListView(); this.registerForContextMenu(lv); lv.setOnItemLongClickListener(this); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); System.out.println("...11configuration is changed..."); } static final String[] PENS = new String[]{ "MONT Blanc", "Gucci", "Parker", "Sailor", "Porsche Design", "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10", "item11" }; protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); activity.openContextMenu(l); System.out.println("...context is called"); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { // TODO Auto-generated method stub System.out.println("...on create context menu..."); super.onCreateContextMenu(menu, v, menuInfo); } public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { System.out.println("...on long click close context menu..."); activity.closeContextMenu(); // TODO Auto-generated method stub return false; }
I don't think it's working smoothly. Calling openContextMenu(l)
will cause item.getMenuInfo()
to be null (inside method onContextItemSelected(MenuItem item)
).
You should call l.showContextMenuForChild(v)
instead of openContextMenu(l)
.