Shashi Kiran
Shashi Kiran

Reputation: 1079

textView.setMovementMethod in Android data binding

I want to achieve clickable link in a textview. I am now migrating all my UI to Android data binding and was wondering how to achieve it.

textView.setMovementMethod.

Any suggestions?

Best,

SK

Upvotes: 2

Views: 1698

Answers (1)

Shashi Kiran
Shashi Kiran

Reputation: 1079

I found out a way to do it. here it is

Create a static method and add BindingAdapter annotation preferably in a separate class

@BindingAdapter("app:specialtext")
    public static void setSpecialText(TextView textView, SpecialText specialText) {
        SpannableString ss = new SpannableString(specialText.getText());

        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                Log.d("tag", "onSpecialClick: ");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(true);
            }
        };

        ss.setSpan(clickableSpan, specialText.getStartIndex(), ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setText(ss);

    }

In your binding layout file

<variable
            name="specialText"
            type="com.example.test.data.SpecialText" />

<TextView
            android:id="@+id/st_textView"
            app:specialtext="@{specialText}"/>

In your activity or fragment where you are using the layout

SpecialText specialText = new TCText();
specialText.setStartIndex(15);
specialText.setText(getActivity().getString(R.string.special_text));
binding.setSpecialText(tcText);

Let me know if you know any better way to do it. Thanks !

Upvotes: 1

Related Questions