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

即使视图已经创建,android文本宽度也返回0,android,text,layout,view,paint,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.m

我有以下代码:

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