安卓TextView设置文本颜色

2017-04-01  本文已影响1902人  奋斗小青年Jerome

在开发中,不免针对部分文字进行特殊的颜色显示,一开始,我用很low的办法就是TextView来拼接,这样既浪费时间又影响性能,所以这总结一下,当然使用Spannable来设置,网上一大堆案例,就不用多介绍,这里介绍一种Html来实现,也有大神写好了工具类

html实现字体颜色变化.png

其原理就是使用html里面的font标签,让字体的颜色和大小变化

String str = "这是第一个<font color='#ff0000'>红色字体</font>的标签";

当我们将这个字符串以Html的方式加载的时候,就会显示出对应的红色字体

textView.setText(Html.fromHtml(str));
Html方式的红色字体

这种方式非常简单,还可以使用size,span等各种html标签实现字体大小,为此我封装了一个方法,可以当做工具类使用,缺点是只能设置一种颜色

 /***
     *
     * @param text 文字
     * @param color 颜色
     * @param childStrArr 需要变色的文字
     * @return
     *可变数组中,可以传入多个想改变的文字
     */
    public StringBuffer setTextColor(String text, String color,String... childStrArr ) {
        StringBuffer stringBuffer = new StringBuffer(text);
        for (int i = 0; i < childStrArr.length; i++) {
            if(text.contains(childStrArr[i])){
                stringBuffer.insert(stringBuffer.indexOf(childStrArr[i]), "<font color='" + color + "'>");
                stringBuffer.insert(stringBuffer.indexOf(childStrArr[i]) + childStrArr[i].length(), "</font>");
            }
        }
        return stringBuffer;
    }

TextView的setMovementMethod方法可以针对Html设置点击时间,这样变色部分就可以响应点击事件
我自定义了一个LinkMovementMethod类,解决其点击的响应,使用中,重写onLinkClicked方法即可

import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;

/**
 * Created by wangjianfeng on 16/11/22.
 * 自定义LinkMovementMethod类,返回超链接的url地址
 */
public class TextViewClickMovement extends LinkMovementMethod {
    private final String TAG = TextViewClickMovement.class.getSimpleName();

    private final OnTextViewClickMovementListener mListener;
    private final GestureDetector mGestureDetector;
    private TextView mWidget;
    private Spannable mBuffer;

    public enum LinkType {

        /**
         * Indicates that phone link was clicked
         */
        PHONE,

        /**
         * Identifies that URL was clicked
         */
        WEB_URL,

        /**
         * Identifies that Email Address was clicked
         */
        EMAIL_ADDRESS,

        /**
         * Indicates that none of above mentioned were clicked
         */
        NONE
    }

    /**
     * Interface used to handle Long clicks on the {@link TextView} and taps
     * on the phone, web, mail links inside of {@link TextView}.
     */
    public interface OnTextViewClickMovementListener {

        /**
         * This method will be invoked when user press and hold
         * finger on the {@link TextView}
         *
         * @param linkText Text which contains link on which user presses.
         * @param linkType Type of the link can be one of {@link LinkType} enumeration
         */
        void onLinkClicked(final String linkText, final LinkType linkType);

        /**
         * @param text Whole text of {@link TextView}
         */
        void onLongClick(final String text);
    }


    public TextViewClickMovement(final OnTextViewClickMovementListener listener, final Context context) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener());
    }

    @Override
    public boolean onTouchEvent(final TextView widget, final Spannable buffer, final MotionEvent event) {

        mWidget = widget;
        mBuffer = buffer;
        mGestureDetector.onTouchEvent(event);

        return false;
    }

    /**
     * Detects various gestures and events.
     * Notify users when a particular motion event has occurred.
     */
    class SimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent event) {
            // Notified when a tap occurs.
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // Notified when a long press occurs.
            final String text = mBuffer.toString();

            if (mListener != null) {
                mListener.onLongClick(text);
            }
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            // Notified when tap occurs.
            final String linkText = getLinkText(mWidget, mBuffer, event);

            LinkType linkType = LinkType.NONE;

            if (Patterns.PHONE.matcher(linkText).matches()) {
                linkType = LinkType.PHONE;
            } else if (Patterns.WEB_URL.matcher(linkText).matches()) {
                linkType = LinkType.WEB_URL;
            } else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
                linkType = LinkType.EMAIL_ADDRESS;
            }

            if (mListener != null) {
                Log.d(TAG, "----> Tap Occurs on TextView with ID: " + mWidget.getId() + "\n" +
                        "Link Text: " + linkText + "\n" +
                        "Link Type: " + linkType + "\n<----");

                mListener.onLinkClicked(linkText, linkType);
            }

            return false;
        }

        private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);


            if (link.length != 0) {

                return link[0].getURL().toString();
            }

            return "";
        }

        private String getLinkString(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                return buffer.subSequence(buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0])).toString();
            }

            return "";
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读