Short-click context menu

Sorry for the stupid question, but what should I change / add in this code - show the context menu by clicking on an item in a list?

public class MyActivity extends ListActivity implements AdapterView.OnItemClickListener { static final String[] COUNTRIES = new String[]{ "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica" }; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES)); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(this); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { Log.e("sdklfjsdkljfl", " <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< "); menu.setHeaderTitle("HELLO"); } public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Log.e("kjhasjkdhkas", "sdkhjkhskaf"); this.openContextMenu(view); } } 
+7
source share
3 answers

Other solutions posted here did not work for me because I used ListFragment. However, the following solutions seem to work well with both ListFragment and ListActivity (or just any old list as a whole):

 public void onListItemClick(ListView l, View v, int position, long id){ l.showContextMenuForChild(v); } 

It is much simpler and more elegant. In fact, this is actually how the ListView class itself initiates a long-click context menu.

+7
source

You need to call registerForContextMenu in the view.

EDITED to add a call to setLongClickable (false)

 public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { registerForContextMenu( view ); view.setLongClickable(false); // undo setting of this flag in registerForContextMenu this.openContextMenu(view); } 

You will also need to actually add menu items, otherwise the menu will not be displayed. Setting the title is not enough.

NOTE. I have not fully traced this yet, but calling registerForContextMenu (view) sets a flag assuming that you want the context menu to last a long time. When this flag is set, the onTouch logic in AbsListView somehow no longer triggers onClick. I don’t have time to completely slip through. It seems that when using a simple adapter such as an ArrayAdapter and using ListActivity with a ListView by default, you will need to decide whether the context menu can appear on a short click or use longclick.

If you do not need long presses, you can configure the context menu for a short press by canceling the flag set in registerForContextMenu (view);

Perhaps someone has more information or more time to dig through the code.

+5
source

Remember to add this after registerForContextMenu() to disable the long click:

 listview.setLongClickable(isRestricted()); 
0
source

All Articles