Android检查Spanned对象是否相等

时间:2013-10-17 09:29:02

标签: android spannable spanned

如何检查两个Spanned对象是否相等(它们是否具有相同的内容和跨度)?我宁愿不实现equals(Spanned span)方法。 :)

1 个答案:

答案 0 :(得分:3)

Android中的span类缺少equalshashCode方法。我不知道为什么。也许这只是一个疏忽? SpannableStringBuilder.equals()方法中还存在一个错误。

解决方法正是您所担心的。例如,如果您使用AbsoluteSizeSpan,则需要对其进行扩展并添加equalshashCode方法。在向SpannableStringBuilder添加范围时使用您的版本而不是框架的版本:

import android.os.Parcel;


public class AbsoluteSizeSpan extends android.text.style.AbsoluteSizeSpan {


    public AbsoluteSizeSpan(int size) {
        super(size);
    }

    public AbsoluteSizeSpan(int size, boolean dip) {
        super(size, dip);
    }

    public AbsoluteSizeSpan(Parcel src) {
        super(src);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AbsoluteSizeSpan that = (AbsoluteSizeSpan) o;

        if (getSize() != that.getSize()) return false;
        return getDip() == that.getDip();
    }

    @Override
    public int hashCode() {
        int result = getSize();
        result = 31 * result + (getDip() ? 1 : 0);
        return result;
    }
}

在Android框架的SpannableStringBuilder.equals()方法中,与未排序的跨度列表相比,已排序的跨度列表。要解决此问题,请覆盖SpannableStringBuilder.equals()

public class SpannableStringBuilder extends android.text.SpannableStringBuilder {

    @Override
    public boolean equals(Object o) {
        if (o instanceof Spanned &&
                toString().equals(o.toString())) {
            Spanned other = (Spanned) o;
            // Check span data
            Object[] otherSpans = other.getSpans(0, other.length(), Object.class);
            Object[] spans = getSpans(0, length(), Object.class);
            if (spans.length == otherSpans.length) {
                for (int i = 0; i < spans.length; ++i) {
                    Object thisSpan = spans[i];
                    Object otherSpan = otherSpans[i];
                    if (thisSpan == this) {
                        if (other != otherSpan ||
                                getSpanStart(thisSpan) != other.getSpanStart(otherSpan) ||
                                getSpanEnd(thisSpan) != other.getSpanEnd(otherSpan) ||
                                getSpanFlags(thisSpan) != other.getSpanFlags(otherSpan)) {
                            return false;
                        }
                    } else if (!thisSpan.equals(otherSpan) ||
                            getSpanStart(thisSpan) != other.getSpanStart(otherSpan) ||
                            getSpanEnd(thisSpan) != other.getSpanEnd(otherSpan) ||
                            getSpanFlags(thisSpan) != other.getSpanFlags(otherSpan)) {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }
}

将范围类的覆盖版本添加到您的SpannableStringBuilder版本。