Tuesday, 19 June 2018

Spannable String With Highlighted Word

  No comments
It takes textview,text to high light and full string as a argument
public void setHighLightedText(TextView tv, String textToHighlight, String fullString) {
        int ofe = fullString.indexOf(textToHighlight, 0);
        Spannable wordToSpan = new SpannableString(fullString);

        try {
            for (int ofs = 0; ofs < fullString.length() && ofe != -1; ofs = ofe + 1) {
                ofe = fullString.indexOf(textToHighlight, ofs);
                if (ofe == -1)
                    break;
                else {
                    // you can change or add more span as per your need
                    wordToSpan.setSpan(new RelativeSizeSpan(2f), ofe, ofe + textToHighlight.length(), 0); // set size
                    wordToSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), ofe, ofe + textToHighlight.length(), 0);// set color
                    tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "setHighLightedText: " + e.getMessage());
        }
    }

public void setClickableString(String wholeValue, TextView yourTextView, String... clickableValue) {
        String value = wholeValue;
        SpannableString spannableString = new SpannableString(value);
        for (String s : clickableValue) {
            int startIndex = value.indexOf(s);
            int endIndex = startIndex + s.length();
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    try {
                        ds.setColor(getActivity().getResources().getColor(R.color.colorPrimary));
                    } catch (Resources.NotFoundException e) {
                        Log.e(TAG, "updateDrawState: "+e.getMessage() );
                    }
                    ds.setUnderlineText(false); // <-- automatic="" clickable="" clickablespan="" do="" endindex="" iew="" important="" in="" inkmovementmethod.getinstance="" onclick="" pre="" public="" remove="" set="" span="" spannablestring="" spanned.span_exclusive_exclusive="" startindex="" t="" this="" underline="" value="" verride="" void="" want="" what="" widget="" will="" with="" without="" won="" work="" you="" yourtextview.setmovementmethod="" yourtextview.settext="">

No comments :

Post a Comment

Loading...