Piezord
Piezord

Reputation: 159

How to make one word in a TextView with a long text from a string clickable?

I have a little question about coding in Java on Android.

So, I have one TextView with a long text from a string. I want to make only one word of this long text clickable, that I can link it to an other Activity.

By the way, I'm new to the Android development, so please don't explain your solution too complicated. Thanks! :)

I have no idea, how I could do this. I also googled after a solution before but didn't find a clear way that worked well. Anyway, I would appreciate your help.

Upvotes: 2

Views: 1703

Answers (4)

Kasra Rahjerdi
Kasra Rahjerdi

Reputation: 2503

What is the outcome you want for the click?

The simplest way to do this would be to apply a URLSpan onto the TextView's contents, but if you want to do something other than view a webpage you can implement your own version of ClickableSpan and make the click do whatever you want.

Edit per your comment:

Making a ClickableSpan go to another activity is really easy, here's the start of the code you'd need for it:

public class MyURLSpan extends ClickableSpan {
        Class<?> mClassToLaunch;

        public MyURLSpan(Class<?> classToLaunch) {
                mClassToLaunch = classToLaunch;
        }

        @Override
        public void onClick(View widget) {
                Intent intent = new Intent(widget.getContext(), mClassToLaunch);
                widget.getContext().startActivity(intent);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
                // If you don't want the default drawstate (blue-underline), comment this super call out.
                super.updateDrawState(ds);
        }
}

Then to use it:

String longText = "your text goes here...";

SpannableString textViewContents = new SpannableString(longText);
textViewContents.setSpan(new MyURLSpan(NextActivity.class), indexToStart, lengthOfClickArea, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

myTextView.setText(textViewContents);

Upvotes: 2

Yogendra
Yogendra

Reputation: 5288

i did not try this but i think if you use below hint then may be You will success. txt.setText(Html.fromHtml("...link...")); txt.setMovementMethod(LinkMovementMethod.getInstance());

select a word on a tap in TextView/EditText

i think it will help.

Upvotes: 0

Phant&#244;maxx
Phant&#244;maxx

Reputation: 38098

Well, you're lucky.
It seems to be possible: see this link.
Another method could be to put an hyperlink in your string.

Upvotes: 1

Matt
Matt

Reputation: 3847

You can create a TextView per-word, and add them to a FlowLayout. Then you can assign OnClick events to any view you want.

The sentance "This is a test" would actually be made up of 4 TextViews, all inside some Layout (maybe a FlowLayout).

There's some details about a FlowLayout in this SO post:

How can I do something like a FlowLayout in Android?

Upvotes: 0

Related Questions