As far as I know, calling measure(0, 0)
on a TextView
causes the view to set its measured width and height to a minimum required by current font/text size:
public class TextViewSizeTest extends AndroidTestCase {
public void testTextWidth() {
TextView view = new TextView(getContext());
view.setTextSize(42);
view.setText("test");
view.measure(0, 0);
assertEquals(212, view.getMeasuredWidth());
}
}
That magic number 212 is the correct answer - the test passes.
But android unit tests aren't really fast - so I tried to use Robolectric instead.
@RunWith(RobolectricTestRunner.class)
public class TextViewSizeTest {
@Test
public void testTextWidth() {
TextView view = new TextView(Robolectric.application);
view.setTextSize(42);
view.setText("test");
view.measure(0, 0);
assertThat(view.getMeasuredWidth(), equalTo(212));
}
}
And now this test fails:
java.lang.AssertionError:
Expected: <212>
but: was <0>
So the question is - am I missing something in test setup/initialization or it is a really problem in Robolectric not properly measuring TextView size?
The right answer is that it is not implemented in Robolectric. Yet. The only relevant function is Paint
's measureText
that returns just text length. It seems I have to extend the Robolectric on my own for this.