开发者

Android selecting a word in either a TextView or EditView

I am trying to figure out an easy way for a user to select a word, preferably by long pressing on the word in a TextView. Basically, I have a TextView filled with text and I would like the user to have the ability开发者_运维知识库 to long press the word and then display a contextmenu so I can execute a database search? Is this possible? I can also switch to an EditText as long as I can make it look like a TextView. Make sense?

Thanks.


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 build 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜