long press on selected text in textview in android

user2586307 picture user2586307 · Jan 8, 2014 · Viewed 15.6k times · Source

In my android app, I have a text view and some text in it. I want that user can see the meaning of the words in a tool tip box when he long press on the word . My problem is that I don’t know how to implement long press in the words.Can some body help me?

Sorry for my poor English.

Answer

Shayan Pourvatan picture Shayan Pourvatan · Jan 8, 2014

use following code:

tv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return false;
        }
});

and import:

import android.view.View.OnLongClickListener;

if you want Click just for some part Of View you need ClickableSpan. copy code from this link.

    SpannableString ss = new SpannableString("Android is a Software stack");
    //ss.setSpan(new StyleSpan(Typeface.ITALIC), 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            startActivity(new Intent(MyActivity.this, NextActivity.class));
        }
    };
    ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    TextView textView = (TextView) findViewById(R.id.hello);
    textView.setText(ss);
    textView.setMovementMethod(LinkMovementMethod.getInstance());