ForegroundColorSpan不生效的解決辦法

SpannableString設置指定字符串的顏色變化

1、在設置字符串文字顏色

2、添加對應的文字點擊跳轉事件

正常的寫法相信大家都會,但是會遇到三種問題

問題一、文字的顏色設置沒有起作用

解決方法:關閉點擊事件或者在updateDrawState()方法中寫下面的方法爲超鏈接文本設置顏色
 ds.setColor(context.getResources().getColor(R.color._4A90E2));

問題二、同時設置了ClickableSpan和ForegroundColorSpan產生了衝突

解決方法:將ForegroundColorSpan替換爲UnderlineSpan,並重寫updateDrawState方法

問題三、點擊對應的變色文字的時候背景顏色不對

解決方法:onClick()方法中調用下面的方法將背景改成透明
((TextView)widget).setHighlightColor(context.getResources().getColor(R.color.transparent));

話不多說,上代碼

注:改變“用戶協議”和“隱私政策”的文字顏色並且帶有跳轉
 /**
     * 同時設置ClickableSpan和ForegroundColorSpan時 指定字符串的顏色無法改變,需要按照下面這樣寫
     * @param context
     * @param textView
     * @description setHighlightColor方法用來改變點擊時的背景透明
     */
    public static void setSpannableString(final Context context,TextView textView) {
        SpannableString spannableString = new SpannableString("我已閱讀並同意 用戶協議 與 隱私政策");
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                ((TextView)widget).setHighlightColor(context.getResources().getColor(R.color.transparent));//點擊後的背景改變透明
                String url = Url.webViewUrl + WebDetailActivity.USER_DISPLINE;
                UrlUtils.parseUrl(context, url);
            }
        },8,12,1);
        spannableString.setSpan(new UnderlineSpan(){
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setColor(context.getResources().getColor(R.color._4A90E2));//設置顏色
                ds.setUnderlineText(false);//去掉下劃線
            }
        },8,12,1);

        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                ((TextView)widget).setHighlightColor(context.getResources().getColor(R.color.transparent));
                String url = Url.webViewUrl + WebDetailActivity.SECURITY_DISPLINE;
                UrlUtils.parseUrl(context, url);
            }
        },15,19,2);
        spannableString.setSpan(new UnderlineSpan(){
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setColor(context.getResources().getColor(R.color._4A90E2));
                ds.setUnderlineText(false);
            }
        },15,19,2);
        textView.setText(spannableString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }

在這裏插入圖片描述

搞定!!!

發佈了97 篇原創文章 · 獲贊 43 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章