How to get Spannable and its color from TextView to write a unit test

Deadly 提交于 2019-12-06 02:19:47

问题


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);
}

I'm trying to write a unit test (using Robolectric) for the TextView tv to ensure that wordTwo is Color.RED. However, I only have a reference to TextView tv. How does one go about such a task?


回答1:


You can get the color of the Spannable from TextView using getSpans() method

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


来源:https://stackoverflow.com/questions/26611533/how-to-get-spannable-and-its-color-from-textview-to-write-a-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!