Android selects a word in TextView or EditView

I am trying to find a simple way for the user to select a word, preferably a long press on the word in TextView. Basically, I have a TextView filled with text, and I would like the user to be able to long press on a word and then display a context menu so that I can search the database? Is it possible? I can also switch to EditText while I can make it look like a TextView. It makes sense?

Thank.

+3
source share
1 answer

Very simple.

First create your TextView and registerForContextMenu ():

private AdapterContextMenuInfo info;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   TextView text = (TextView) findViewById(R.id.txtbtn);
   text.setText("Click Me!");

   registerForContextMenu(text);
}

Then create your ContextMenu:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}   
@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.call: 

        String phone="555-555-555";
        String toDial="tel:"+phone.toString();

        Uri uri = Uri.parse(toDial);
        Intent it = new Intent(Intent.ACTION_DIAL, uri);  
        startActivity(it);  

    return true;

    default:
    return super.onContextItemSelected(item);
    }
}

context_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/call"
          android:title="CALL" />
</menu>
0

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


All Articles