Android 如何获得线性布局的大小
我试着得到线性布局的尺寸。在以下代码中,我始终得到iactualHeight=0:Android 如何获得线性布局的大小,android,android-linearlayout,Android,Android Linearlayout,我试着得到线性布局的尺寸。在以下代码中,我始终得到iactualHeight=0: li=(LinearLayout)findViewById(R.id.textviewerbuttonlayout); li.requestLayout(); int iactualHeight=li.getLayoutParams().height; 我的布局定义如下: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/and
li=(LinearLayout)findViewById(R.id.textviewerbuttonlayout);
li.requestLayout();
int iactualHeight=li.getLayoutParams().height;
我的布局定义如下:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#FFFFFF"
android:id="@+id/textviewerlayout"
android:orientation="vertical">
<WebView
android:id="@+id/mywebview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="22" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textviewerbuttonlayout"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="#FFFFFF"
android:orientation="horizontal" >
.... BUTTONS .....
</LinearLayout>
</LinearLayout>
.... 按钮。。。。。
有人知道吗?一旦创建完成,您将无法获得值unitl
。因此,请将这些值添加到onResume()
或onStart()
另一个选项是使用globallayoutlistener
(如果您想在onCreate中获取高度),以便在添加li(您的布局)时收到通知
ViewTreeObserver observer= li.getViewTreeObserver();
observer.addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Log.d("Log", "Height: " + li.getHeight());
Log.d("Log", "Width: " + li.getWidth());
}
});
问题是你要求的高度太早了。看一看
获得保证高度的最简单方法是使用addOnLayoutChangedListener:
View myView = findViewById(R.id.my_view);
myView.addOnLayoutChangedListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
// its possible that the layout is not complete in which case
// we will get all zero values for the positions, so ignore the event
if (left == 0 && top == 0 && right == 0 && bottom == 0) {
return;
}
int height = top - bottom;
}
});
非常感谢。在onStart中,我仍然得到0。在OnGlobalLayoutListener中,我得到了正确的值。所以你的快速回答非常有用。
View myView = findViewById(R.id.my_view);
myView.addOnLayoutChangedListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
// its possible that the layout is not complete in which case
// we will get all zero values for the positions, so ignore the event
if (left == 0 && top == 0 && right == 0 && bottom == 0) {
return;
}
int height = top - bottom;
}
});