我有此代码:
public AccountMenuBodyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.account_menu_body, this, true);
myAccountView = findViewById(R.id.my_account);
}
@VisibleForTesting
String setChipTextWithCorrectLength(String longDesc, String mediumDesc, String shortDesc, int clipWidth) {
if (textWidthPixels(longDesc) > clipWidth) {
if (textWidthPixels(mediumDesc) > clipWidth) {
return shortDesc;
} else {
return mediumDesc;
}
}
return longDesc;
}
public double textWidthPixels(String text) {
Rect bounds = new Rect();
Paint textPaint = myAccountView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
return bounds.width();
}
所以充气机会创建mAccountView
。
但是当我运行单元测试时,我看到textWidthPixels(..)
返回0
和bounds = Rect(0, 0 - 0, 0)
为什么全为零?
测试:
@Test
public void clipWithMediumText() throws Exception {
String clipText = accountMenuBodyView
.setChipTextWithCorrectLength("very very very long text", "medium text", "short", 20);
assertThat(clipText).isEqualTo("medium text");
}