我想在 onCreate() 方法中获取 Middle(Body) 布局的高度/宽度。
我的 main.xml 是:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_Main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/main_bg11" >
<RelativeLayout
android:id="@+id/rl_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<include layout="@layout/title" />
</RelativeLayout>
<ScrollView
android:id="@+id/svtest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/rl_music_controller"
android:layout_below="@+id/rl_title" >
<RelativeLayout
android:id="@+id/rl12"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<TableLayout
android:id="@+id/tbl_vandana"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_horizontal"
android:paddingTop="30dp" >
</TableLayout>
</RelativeLayout>
</ScrollView>
<RelativeLayout
android:id="@+id/rl_music_controller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<include layout="@layout/controller" />
</RelativeLayout>
我在 TableLayout 中动态添加 Textview。 编号:
rl_title 是我的标题布局
svtest 是我的中间(正文)内容。
rl_music_controller 是我的页脚布局。
我指的是 this link .但是我不明白我到底在做什么?
最佳答案
当布局宽度和高度设置为Added: This applies for all types of layout. Not only ScrollView.
match_parent
和 wrap_content时,getWidth()
和 getHeight()
方法返回 0
。尺寸未测量。
用于获取测量尺寸的正确方法是 getMeasuredWidth()
和 getMeasuredHeight()
。
Note: measured dimensions in onCreate method are not initialized yet.
正确的方式和位置是(snippet可以添加到任何地方,包括onCreate
):
ScrollView scrollView = (ScrollView)findViewById(R.id.svtest);
ViewTreeObserver vto = scrollView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16)
scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
else
scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
int width = scrollView.getMeasuredWidth();
int height = scrollView.getMeasuredHeight();
// postpone any calculation depend on it to here.
// regardless what it is. UI or http connection.
}
});
一些答案试图在 onStart() 方法中做到这一点。但是,他们尝试调用 getWidth()
和 getHeight()
方法。试试 getMeasuredWidth()
和 getMeasuredHeight()
。它无需添加 OnGlobalLayoutListener
即可工作。仅当您想在 on create 方法中获取维度时才需要监听器。在以后的任何阶段都不需要监听器,因为届时将测量尺寸(例如在开始时)。
关于Android:动态获取Body Layout的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17541993/