我尝试获得线性布局的大小。我在下面的代码中总是得到iactualHeight = 0:
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>
有人有什么想法吗?
答案 0 :(得分:2)
您无法获得价值unitl onCreate
结束。请在onResume()
或onStart()
int height= li.getHeight();
int width = li.getWidth();
另一种选择是使用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());
}
});
答案 1 :(得分:0)
问题是你要求过早的高度。看看how android draws views。
获得保证身高的最简单方法是使用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;
}
});