0

例如,这是mButton

<Button
   android:id="@+id/mbtn"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="mButton" />

这就是我试图获得高度的方式:

int height = mButton.getLayoutParams.height;

但是当我记录它时,它说高度是-2。我认为这可能是“wrap_content”的 int 值。那么我怎样才能得到实际的高度呢?谢谢!

4

3 回答 3

3

如果您想在活动中获取视图的宽度或高度,您可以使用此方法..

yourview.getHeight(); 

初始化按钮后返回零(0),因为在将其添加到窗口后,它只有一个宽度。在下面的方法中,您可以查看视图的高度和宽度。

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    yourview.getHeight();
    yourview.getWidth();
}
于 2013-11-04T06:32:40.707 回答
1

覆盖方法 onWindowFocusChanged(boolean hasFocus);

在里面写你的代码,

@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mbtn.getHeight();
mbtn.getWidth();
}

它将给出视图尺寸的正确结果。

于 2013-11-04T06:55:23.713 回答
0

布局发生后调用View.getHeight()

public final int getHeight()

返回视图的高度。

返回
视图的高度,以像素为单位。

如您所料,layoutParams.height这只是wrap_content您的情况下的值,即-2。您可以设置layoutParams.height为所需的高度,但即便如此,它也不一定是所有布局完成后视图实际最终达到的高度。

于 2013-11-04T06:32:12.843 回答