我一直在尝试测量另一个RelativeLayout中RelativeLayout中视图的像素尺寸:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60"
>
...
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/labels_placeholder"
android:id="@+id/player_section_layout"
>
<LinearLayout
android:id="@+id/player_section_background"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="100">
<!--The view above is what I'm trying to measure-->
<LinearLayout
android:id="@+id/player_section_background_left"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="50"
android:background="#AAAAAA"
android:orientation="horizontal" />
<LinearLayout
android:id="@+id/player_section_background_right"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="50"
android:background="#DD0000"
android:orientation="horizontal" />
</LinearLayout>
<HorizontalScrollView
android:id="@+id/player_section"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_alignTop="@id/player_section_background">
<ImageView
android:id="@+id/waveform_placeholder"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:scaleType="centerInside"
/>
</HorizontalScrollView>
</RelativeLayout>
</RelativeLayout>
我尝试在片段的onCreateView()中引用它后立即调用getMeasuredHeight()和getMeasuredWidth():
waveformBackground = (LinearLayout)result.findViewById(R.id.player_section_background);
waveformBackground.post(new Runnable() {
@Override
public void run() {
Log.i("bckg_layout_dims", waveformBackground.getMeasuredWidth()+" "+waveformBackground.getMeasuredHeight());
}
});
两者都返回0。
在绘制视图之前,我确实听到过有关它无效的信息,但我不知道它何时完成绘制。是在OnCreateView
之后,如果是,我可以在OnActivityResult
中调用它吗?
答案 0 :(得分:0)
您面临的问题是因为在您要求高度和宽度后绘制视图。我使用ViewTreeObserver不断监听视图中的更改,并可以在绘制视图后访问测量。我不确定这是你问题的最佳解决方案,但你应该研究一下。这是一个例子:
mTitleContainer.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int toolBarHeight = mTitle.getHeight() + mSubtitle.getHeight() + (int) TOOLBARPADDING;
if (toolBarHeight != mLastTitleHeight) {
CollapsingToolbarLayout.LayoutParams layoutParams = (CollapsingToolbarLayout.LayoutParams) mTitleToolbar.getLayoutParams();
layoutParams.height = toolBarHeight;
mTitleToolbar.setLayoutParams(layoutParams);
mLastTitleHeight = toolBarHeight;
}
}
}
);