Android實現加載富文本以及SpannableString、SpannableStringBuilder實現部分文字可以點擊,更換顏色

??常用開發工具類和自定義view,無恥的求個star:
??https://github.com/AbrahamCaiJin/CommonUtilLibrary
??最近項目中要實現部分文字變顏色,并且是可點擊的。網上找了一下,實現的方式是Android端加載富文本,如果你會js的話,那就方便了,表示本人不怎么會,而且項目框架和界面已經確定了,不可能再改,所以只能試一試其他的方式。 SpannableString、SpannableStringBuilder的詳細具體用法可以參考這個博客: http://blog.csdn.net/qq_24530405/article/details/50506519
第一種方式:
??如果文字是固定不變的,可以在String.xml中配置的,可以采用網上最普遍的方式。
??我們先來看看效果:

這里寫圖片描述

??文字的顏色改變了,并且變紅的兩個字是有點擊事件的。
??下面直接看代碼,布局文件就只有一個TextView,非常簡單。

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class FirstActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        TextView textView = (TextView) findViewById(R.id.text1);
        SpannableStringBuilder spannable = new SpannableStringBuilder("可以點擊的");
        //設置文字的前景色
        spannable.setSpan(new ForegroundColorSpan(Color.RED),2,4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //這個一定要記得設置,不然點擊不生效
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        spannable.setSpan(new TextClick(),2,4 , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);
    }
    private class TextClick extends ClickableSpan{
        @Override
        public void onClick(View widget) {
            //在此處理點擊事件
            Log.e("------->", "點擊了");
        }
        
        @Override
        public void updateDrawState(TextPaint ds) {
//            ds.setColor(ds.linkColor);        
//            ds.setUnderlineText(true);
        }
    }
}

注意:這里使用的是SpannableStringBuilder,這和java里面StringBuilder性質是一樣的,有append方法,可以不斷的追加。

第二種方式:
??通過正則表達式。
??還是先看效果,顏色改變了,并且是可點擊的。


這里寫圖片描述

這里,我使用的是自定義TextView,下面貼上代碼。

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
 
public class MyTextView extends TextView
{
 
    public MyTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
 
    public void setSpecifiedTextsColor(String text, String specifiedTexts, int color)
    {   
        List<Integer> sTextsStartList = new ArrayList<>();
         
        int sTextLength = specifiedTexts.length();
        String temp = text;
        int lengthFront = 0;//記錄被找出后前面的字段的長度
        int start = -1;
        do
        {
            start = temp.indexOf(specifiedTexts);
             
            if(start != -1)
            {
                start = start + lengthFront;
                sTextsStartList.add(start);
                lengthFront = start + sTextLength;
                temp = text.substring(lengthFront);
            }
             
        }while(start != -1);
         
        SpannableStringBuilder styledText = new SpannableStringBuilder(text);
        for(Integer i : sTextsStartList)
        {
            styledText.setSpan(
                    new ForegroundColorSpan(color), 
                    i, 
                    i + sTextLength, 
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            //這個一定要記得設置,不然點擊不生效
            setMovementMethod(LinkMovementMethod.getInstance());
            styledText.setSpan(new TextClick(),i,i + sTextLength , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(styledText);
    }
    private class TextClick extends ClickableSpan{
        @Override
        public void onClick(View widget) {
            //在此處理點擊事件
            Log.e("------->", "點擊了");
//            widget.seth
        }
                @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);        
            ds.setUnderlineText(true);
        }
    }
   }

然后是在activity中使用的代碼:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;

public class SecondActivity extends Activity {
private MyTextView textView;
    
    public String text = "Android是一種基于Linux的自由及開放源代碼的操作系統,主要使用于移動設備,如智能手機和平板電腦,由Google公司和開放手機聯盟領導及開發。尚未有統一中文名稱,中國大陸地區較多人使用“安卓”或“安致”。Android操作系統最初由Andy Rubin開發,主要支持手機。2005年8月由Google收購注資。2007年11月,Google與84家硬件制造商、軟件開發商及電信營運商組建開放手機聯盟共同研發改良Android系統。隨后Google以Apache開源許可證的授權方式,發布了Android的源代碼。第一部Android智能手機發布于2008年10月。Android逐漸擴展到平板電腦及其他領域上,如電視、數碼相機、游戲機等。2011年第一季度,Android在全球的市場份額首次超過塞班系統,躍居全球第一。 2013年的第四季度,Android平臺手機的全球市場份額已經達到78.1%。[1] 2013年09月24日谷歌開發的操作系統Android在迎來了5歲生日,全世界采用這款系統的設備數量已經達到10億臺。";
     
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
      // 正則表達式。表示連續6位的數字,可以在這邊修改成自己所要的格式  
      Pattern pattern = Pattern.compile("[1-9]\\d*[TBU][1-9]\\d*");  
      String code = "";
      // 匹配短信內容  
      Matcher matcher = pattern.matcher(text);  
      if (matcher.find()) {  
          code = matcher.group(0);  
      }  
      
        textView = (MyTextView)findViewById(R.id.tv);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setSpecifiedTextsColor(text, "Android", Color.parseColor("#FF0000"));
        textView.setHighlightColor(getResources().getColor(android.R.color.transparent));//設置點擊后的顏色
    }
}

第三種方式:
??是在github上看到的,具體是那兒,忘了,不好意思。
??這個和第二個是類似的,這個也是自定義TextView,只不過這個是在xml文件中進行關鍵字的配置。
??先看效果:


這里寫圖片描述
這里寫圖片描述

貼上代碼:

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

/**
 * Created by Shaolei on 2016/10/10.
 */
public class AutoLinkStyleTextView extends TextView {

    private static String DEFAULT_TEXT_VALUE = null;
    private static int DEFAULT_COLOR = Color.parseColor("#f23218");
    private static boolean HAS_UNDER_LINE = true;

    private ClickCallBack mClickCallBack;

    public AutoLinkStyleTextView(Context context) {
        this(context, null);
    }

    public AutoLinkStyleTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoLinkStyleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoLinkStyleTextView, defStyleAttr, 0);
        DEFAULT_TEXT_VALUE = typedArray.getString(R.styleable.AutoLinkStyleTextView_AutoLinkStyleTextView_text_value);
        DEFAULT_COLOR = typedArray.getColor(R.styleable.AutoLinkStyleTextView_AutoLinkStyleTextView_default_color, DEFAULT_COLOR);
        HAS_UNDER_LINE = typedArray.getBoolean(R.styleable.AutoLinkStyleTextView_AutoLinkStyleTextView_has_under_line, HAS_UNDER_LINE);
//        setAutoLinkStyleTextView_text_value("“購買”,“須知”");
        addStyle();
        typedArray.recycle();
    }

    private void addStyle(){
        if (!TextUtils.isEmpty(DEFAULT_TEXT_VALUE) && DEFAULT_TEXT_VALUE.contains(",")) {
            String[] values = DEFAULT_TEXT_VALUE.split(",");
//            Log.e("---------->值", DEFAULT_TEXT_VALUE);
            SpannableString spannableString = new SpannableString(getText().toString().trim());
            for (int i = 0; i < values.length; i++){
                final int position = i;
                spannableString.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        if (mClickCallBack != null) mClickCallBack.onClick(position);
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(DEFAULT_COLOR);
                        ds.setUnderlineText(HAS_UNDER_LINE);
                    }
                }, getText().toString().trim().indexOf(values[i]), getText().toString().trim().indexOf(values[i]) + values[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            setText(spannableString);
            setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

//    public void setAutoLinkStyleTextView_text_value(String text) {
//        DEFAULT_TEXT_VALUE = text;
//        Log.e("-------------", "調用幾次"+DEFAULT_TEXT_VALUE);
//        addStyle();
//    };
    public void setOnClickCallBack(ClickCallBack clickCallBack){
        this.mClickCallBack = clickCallBack;
    }

    public interface ClickCallBack{
        void onClick(int position);
    }
}

??然后是在activity里面的調用:

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class ThreeActivity extends Activity {
    private AutoLinkStyleTextView autoLinkStyleTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three);
        autoLinkStyleTextView = (AutoLinkStyleTextView) findViewById(R.id.tv);
        autoLinkStyleTextView.setOnClickCallBack(new AutoLinkStyleTextView.ClickCallBack() {
                    @Override
                    public void onClick(int position) {
                        if (position == 0) {
                            Toast.makeText(ThreeActivity.this, "購買須知",
                                    Toast.LENGTH_SHORT).show();
                        } else if (position == 1) {
                            Toast.makeText(ThreeActivity.this, "用戶條款",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}

第四種方式:
??使用Html.fromHtml來加載富文本。
??先看效果,第一次錄制gif文件,效果有點差哈,不要介意。


這里寫圖片描述

??下面看見代碼:
??布局文件就兩個TextView。

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class FourActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);
         TextView tips = (TextView) findViewById(R.id.text);
//         https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png
          String str = "單擊打開 <a ;
          tips.setText(Html.fromHtml(str));
          // Html.fromHtml(
          // "<b>text3:</b>  Text with a " +
          // "<a href=\"http://www.google.com\">link</a> " +
          // "created in the Java source code using HTML."))
          tips.setMovementMethod(LinkMovementMethod.getInstance());
         TextView protocalTv = (TextView) findViewById(R.id.text1);
         String str1 =
         "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png";
         SpannableString spannableString1 = new SpannableString(str1);
        
         spannableString1.setSpan(new ClickableSpan() {
         public void onClick(View widget) {
         Toast.makeText(getApplicationContext(), "點擊了第一處", 0).show();
        
         }
         }, str1.length() - 5, str1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
         spannableString1.setSpan(new ForegroundColorSpan(getResources()
         .getColor(android.R.color.holo_blue_bright)), str1.length() - 5,
         str1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
         spannableString1.setSpan(new ClickableSpan() {
         public void onClick(View widget) {
         Toast.makeText(getApplicationContext(), "點擊了第二處", 0).show();
        
         }
         }, 7, 14, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
         spannableString1.setSpan(new ForegroundColorSpan(getResources()
         .getColor(android.R.color.holo_red_light)), 7, 14,
         Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
         protocalTv.setText(spannableString1);
         protocalTv.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

最后給出下載鏈接:
http://download.csdn.net/detail/u014727709/9710194
轉載自: http://blog.csdn.net/u014727709/article/details/53610381
歡迎start,歡迎評論,歡迎指正
更多特效點擊這兒: http://blog.csdn.net/u014727709/article/details/53610381

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容