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

sud*_*der 5 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);
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试为TextView tv编写一个单元测试(使用Robolectric)以确保wordTwo是Color.RED.但是,我只提到了TextView tv.怎么去做这样的任务?

Nik*_*ski 10

您可以获取Spannablefrom TextViewusing getSpans()方法的颜色

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

  • 我得到一个类强制转换异常,除非我使用`SpannedString`而不是`SpannableStringBuilder`. (3认同)