Show context menu when link is longer pressed in TextView

I have a TextView with its MovementMethod set to LinkMovementMethod . The text added to the TextView is a combination of plain text and URLs. For URLs, I would like to offer a context menu when the URL is long pressed to perform actions such as copying the address. I looked at the source for LinkMovementMethod , but it did not seem to have a long pressed linked code that I could override. Any ideas on how to get around this?

+5
android textview contextmenu
source share
1 answer

You can simply use registerForContextMenu, for example:

  TextView tv = new TextView(this); registerForContextMenu(tv); 

and then override onCreateContextMenu to create the menu

 @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Create your context menu here menu.setHeaderTitle("Context Menu"); menu.add(0, v.getId(), 0, "Action 1"); } 

where you can use the view identifier to convey events that occur when you click a menu item to distinguish which view is called an event.

 @Override public boolean onContextItemSelected(MenuItem item) { // Call your function to preform for buttons pressed in a context menu // can use item.getTitle() or similar to find out button pressed // item.getItemID() will return the v.getID() that we passed before } 
+13
source share

All Articles