即使已创建视图,Android文本宽度也返回0

时间:2018-08-28 09:40:53

标签: android text layout view paint

我有此代码:

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

0 个答案:

没有答案