如何从TextView获取Spannable及其颜色以编写单元测试

时间:2014-10-28 14:58:22

标签: android textview robolectric

private void createStringEndingInRedColor(TextView tv, String word1, String word2) {
    Spannable word = new SpannableString(word1);
    tv.setText(word);

    Spannable wordTwo = new SpannableString(word2);

    wordTwo.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(Color.RED)), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    tv.append(wordTwo);
}

我正在尝试为TextView tv编写单元测试(使用Robolectric),以确保wordTwo为Color.RED。但是,我只提到了TextView tv。如何进行这样的任务呢?

1 个答案:

答案 0 :(得分:10)

您可以使用Spannable方法从TextView获取getSpans()的颜色

ForegroundColorSpan[] colorSpans = ((SpannableString)textView.getText()).getSpans(0, textView.getText().length(), ForegroundColorSpan.class);
assertTrue(colorSpans[0].getForegroundColor() == Color.RED)